From ac6b084f3197c40b0fd7ee56209890f9be035b1b Mon Sep 17 00:00:00 2001 From: Antonis Lilis Date: Tue, 10 Nov 2026 09:50:26 +0100 Subject: [PATCH 01/51] feat(android): Connect traces with web content in a WebView (#6395) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(android): Connect traces with web content in a WebView Add SentryWebViewTracing.addTracePropagation, which writes the current trace into pages from allowed hosts as sentry-trace and baggage meta tags before any page script runs, so @sentry/browser in the page continues the trace on pageload. It uses androidx.webkit's document-start script, a compileOnly dependency checked at runtime, and adds a sample screen and an instrumented test. Refs JAVA-716 Co-Authored-By: Claude Opus 5.5 * changelog Co-Authored-By: Claude Opus 5.5 * fix(android): Keep non-default ports and handle old androidx.webkit A WebView origin rule without a port only matches port 443, so a non-default port in an allowedHosts entry is now kept in the rule. androidx.webkit is compileOnly, so an app may ship an older version than the SDK was compiled against. A LinkageError is now caught, like for androidx.activity in the feedback form, and the call returns false. Co-Authored-By: Claude Opus 5.5 * fix(android): Remove the previous WebView script after an off-thread call A call off the WebView's thread returns false without touching the WebView, which left Sentry's previous script installed. The removal is now posted to the WebView's thread, and skipped if a call on that thread replaced the script in the meantime. Co-Authored-By: Claude Opus 5.5 * fix(android): Track WebView script replacements per WebView The off-thread cleanup compared against one counter shared by all WebViews, bumped before the replacement finished. A concurrent off-thread call could then remove a script that was just installed, and a call on another WebView cancelled this WebView's cleanup. The count is now kept per WebView, with weak keys, and bumped once the replacement is done. Co-Authored-By: Claude Opus 5.5 * ref(samples): Move the WebView trace screen to the Tracing tab The sample no longer shows an iframe; the instrumented test in sentry-uitest-android still checks that iframes don't get the trace. Co-Authored-By: Claude Opus 5.5 * fix(android): Match internationalized hosts in WebView trace propagation The page's location.hostname is in punycode, so an allowedHosts entry like münchen.de never matched. Non-ASCII entries are now converted with IDN.toASCII, and entries that cannot be converted are dropped. Co-Authored-By: Claude Opus 5.5 * docs(changelog): Shorten WebView trace propagation entry Co-Authored-By: Claude Opus 5.5 * fix(android): Never throw from the posted WebView script removal Co-Authored-By: Claude Opus 5.5 * fix(android): Rethrow fatal errors from the posted WebView script removal Co-Authored-By: Claude Opus 5.5 * Add docs link to the changelog * Updated link to WebView documentation in CHANGELOG. --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 4 + gradle/libs.versions.toml | 2 + .../api/sentry-android-core.api | 5 + sentry-android-core/build.gradle.kts | 4 + sentry-android-core/proguard-rules.pro | 6 + .../core/AndroidxWebViewScriptInstaller.java | 48 ++ .../android/core/SentryWebViewTracing.java | 255 +++++++++++ .../android/core/WebViewScriptInstaller.java | 26 ++ .../core/WebViewTracePropagationScript.java | 291 +++++++++++++ .../src/main/res/values/ids.xml | 5 + .../android/core/SentryWebViewTracingTest.kt | 410 ++++++++++++++++++ .../core/WebViewTracePropagationScriptTest.kt | 368 ++++++++++++++++ .../sentry-uitest-android/build.gradle.kts | 1 + .../android/WebViewTracePropagationTest.kt | 45 ++ .../src/main/AndroidManifest.xml | 1 + .../src/main/assets/webview/iframe.html | 15 + .../src/main/assets/webview/index.html | 16 + .../uitest/android/WebViewTraceActivity.kt | 66 +++ .../sentry-samples-android/build.gradle.kts | 1 + .../src/main/AndroidManifest.xml | 5 + .../src/main/assets/webview/index.html | 44 ++ .../io/sentry/samples/android/MainActivity.kt | 10 + .../sentry/samples/android/WebViewActivity.kt | 129 ++++++ 23 files changed, 1757 insertions(+) create mode 100644 sentry-android-core/src/main/java/io/sentry/android/core/AndroidxWebViewScriptInstaller.java create mode 100644 sentry-android-core/src/main/java/io/sentry/android/core/SentryWebViewTracing.java create mode 100644 sentry-android-core/src/main/java/io/sentry/android/core/WebViewScriptInstaller.java create mode 100644 sentry-android-core/src/main/java/io/sentry/android/core/WebViewTracePropagationScript.java create mode 100644 sentry-android-core/src/main/res/values/ids.xml create mode 100644 sentry-android-core/src/test/java/io/sentry/android/core/SentryWebViewTracingTest.kt create mode 100644 sentry-android-core/src/test/java/io/sentry/android/core/WebViewTracePropagationScriptTest.kt create mode 100644 sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/WebViewTracePropagationTest.kt create mode 100644 sentry-android-integration-tests/sentry-uitest-android/src/main/assets/webview/iframe.html create mode 100644 sentry-android-integration-tests/sentry-uitest-android/src/main/assets/webview/index.html create mode 100644 sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/WebViewTraceActivity.kt create mode 100644 sentry-samples/sentry-samples-android/src/main/assets/webview/index.html create mode 100644 sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/WebViewActivity.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e1e21e6d22..58951b26c6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ ### Features +- 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. + - 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)) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index e8175ecec06..25e67951b37 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -126,6 +126,7 @@ 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" } @@ -303,6 +304,7 @@ 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" } roboelectric = { module = "org.robolectric:robolectric", version = "4.15" } [bundles] diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 62d9b0d4960..85c33e2772d 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -628,6 +628,11 @@ public abstract interface class io/sentry/android/core/SentryUserFeedbackForm$Op public abstract fun configure (Landroid/content/Context;Lio/sentry/SentryFeedbackOptions;)V } +public final class io/sentry/android/core/SentryWebViewTracing { + public static fun addTracePropagation (Landroid/webkit/WebView;Ljava/util/List;)Z + public static fun addTracePropagation (Landroid/webkit/WebView;[Ljava/lang/String;)Z +} + 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 fun (Lio/sentry/android/core/SentryAndroidOptions;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;)V diff --git a/sentry-android-core/build.gradle.kts b/sentry-android-core/build.gradle.kts index af5a010d309..c261c56f785 100644 --- a/sentry-android-core/build.gradle.kts +++ b/sentry-android-core/build.gradle.kts @@ -104,6 +104,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) @@ -132,6 +134,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 eadc6917af7..34fc51f709a 100644 --- a/sentry-android-core/proguard-rules.pro +++ b/sentry-android-core/proguard-rules.pro @@ -30,6 +30,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/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/SentryWebViewTracing.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryWebViewTracing.java new file mode 100644 index 00000000000..ad15c82ab3a --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryWebViewTracing.java @@ -0,0 +1,255 @@ +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.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)}. + * + * @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/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/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/SentryWebViewTracingTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryWebViewTracingTest.kt new file mode 100644 index 00000000000..fd532c2ff65 --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryWebViewTracingTest.kt @@ -0,0 +1,410 @@ +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.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.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 `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/WebViewTracePropagationScriptTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/WebViewTracePropagationScriptTest.kt new file mode 100644 index 00000000000..210bdf80dad --- /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-integration-tests/sentry-uitest-android/build.gradle.kts b/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts index 5539cac6944..d5f90f76004 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts +++ b/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts @@ -108,6 +108,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) 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/main/AndroidManifest.xml b/sentry-android-integration-tests/sentry-uitest-android/src/main/AndroidManifest.xml index 6bcad62e6de..624520b5b4c 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 @@ -15,6 +15,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/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-samples/sentry-samples-android/build.gradle.kts b/sentry-samples/sentry-samples-android/build.gradle.kts index 8fb29bb4ecd..3a1de5a704a 100644 --- a/sentry-samples/sentry-samples-android/build.gradle.kts +++ b/sentry-samples/sentry-samples-android/build.gradle.kts @@ -213,6 +213,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) diff --git a/sentry-samples/sentry-samples-android/src/main/AndroidManifest.xml b/sentry-samples/sentry-samples-android/src/main/AndroidManifest.xml index f0f2895e0b2..5b0f8dd715e 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" /> + + diff --git a/sentry-samples/sentry-samples-android/src/main/assets/webview/index.html b/sentry-samples/sentry-samples-android/src/main/assets/webview/index.html new file mode 100644 index 00000000000..889ef2fb270 --- /dev/null +++ b/sentry-samples/sentry-samples-android/src/main/assets/webview/index.html @@ -0,0 +1,44 @@ + + + + + + + + + + +

WebView page

+

Injected sentry-trace:

+
(none, not injected)
+ + + 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 9660f52ed36..76b6a69f3fb 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 @@ -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) + } + } + } } } 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..b0feb66a0e6 --- /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" + } +} From 144b2eedd2430a804fcea5b2e5a0de724bc5ae56 Mon Sep 17 00:00:00 2001 From: Alexander Dinauer Date: Tue, 10 Nov 2026 10:15:49 +0100 Subject: [PATCH 02/51] chore(deps): Ignore OpenTelemetry Dependabot updates (#6531) Prevent independent OpenTelemetry dependency bumps because the SDK, agent, alpha artifacts, and semantic conventions must be updated together. Co-authored-by: Codex --- .github/dependabot.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d1593330dd3..7cee6759bd3 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -19,6 +19,7 @@ updates: interval: "daily" ignore: - dependency-name: "org.springframework.boot*" + - dependency-name: "io.opentelemetry*" commit-message: prefix: "chore(deps)" - package-ecosystem: "github-actions" From 50ebe9e9f2bd8f311d467d2da99e8af5d540dba2 Mon Sep 17 00:00:00 2001 From: Antonis Lilis Date: Tue, 10 Nov 2026 10:20:03 +0100 Subject: [PATCH 03/51] feat(android): Add WebView tracing options with allowed hosts (#6516) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(android): Connect traces with web content in a WebView Add SentryWebViewTracing.addTracePropagation, which writes the current trace into pages from allowed hosts as sentry-trace and baggage meta tags before any page script runs, so @sentry/browser in the page continues the trace on pageload. It uses androidx.webkit's document-start script, a compileOnly dependency checked at runtime, and adds a sample screen and an instrumented test. Refs JAVA-716 Co-Authored-By: Claude Opus 5.5 * changelog Co-Authored-By: Claude Opus 5.5 * fix(android): Keep non-default ports and handle old androidx.webkit A WebView origin rule without a port only matches port 443, so a non-default port in an allowedHosts entry is now kept in the rule. androidx.webkit is compileOnly, so an app may ship an older version than the SDK was compiled against. A LinkageError is now caught, like for androidx.activity in the feedback form, and the call returns false. Co-Authored-By: Claude Opus 5.5 * fix(android): Remove the previous WebView script after an off-thread call A call off the WebView's thread returns false without touching the WebView, which left Sentry's previous script installed. The removal is now posted to the WebView's thread, and skipped if a call on that thread replaced the script in the meantime. Co-Authored-By: Claude Opus 5.5 * fix(android): Track WebView script replacements per WebView The off-thread cleanup compared against one counter shared by all WebViews, bumped before the replacement finished. A concurrent off-thread call could then remove a script that was just installed, and a call on another WebView cancelled this WebView's cleanup. The count is now kept per WebView, with weak keys, and bumped once the replacement is done. Co-Authored-By: Claude Opus 5.5 * ref(samples): Move the WebView trace screen to the Tracing tab The sample no longer shows an iframe; the instrumented test in sentry-uitest-android still checks that iframes don't get the trace. Co-Authored-By: Claude Opus 5.5 * fix(android): Match internationalized hosts in WebView trace propagation The page's location.hostname is in punycode, so an allowedHosts entry like münchen.de never matched. Non-ASCII entries are now converted with IDN.toASCII, and entries that cannot be converted are dropped. Co-Authored-By: Claude Opus 5.5 * docs(changelog): Shorten WebView trace propagation entry Co-Authored-By: Claude Opus 5.5 * fix(android): Never throw from the posted WebView script removal Co-Authored-By: Claude Opus 5.5 * fix(android): Rethrow fatal errors from the posted WebView script removal Co-Authored-By: Claude Opus 5.5 * Add docs link to the changelog * Updated link to WebView documentation in CHANGELOG. * feat(android): Use tracePropagationTargets as the default WebView hosts Co-Authored-By: Claude Opus 5.5 * feat(android): Add WebView tracing options with allowed hosts Co-Authored-By: Claude Opus 5.5 * ref(android): Default WebView allowed hosts to an empty list Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../api/sentry-android-core.api | 8 ++++ .../android/core/ManifestMetadataReader.java | 8 ++++ .../android/core/SentryAndroidOptions.java | 13 ++++++ .../android/core/SentryWebViewTracing.java | 20 ++++++++++ .../core/SentryWebViewTracingOptions.java | 34 ++++++++++++++++ .../core/ManifestMetadataReaderTest.kt | 26 ++++++++++++ .../android/core/SentryAndroidOptionsTest.kt | 12 ++++++ .../android/core/SentryWebViewTracingTest.kt | 40 +++++++++++++++++++ 9 files changed, 162 insertions(+) create mode 100644 sentry-android-core/src/main/java/io/sentry/android/core/SentryWebViewTracingOptions.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 58951b26c6b..8ddc5b5d7bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - 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)) diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 85c33e2772d..b14b6873e21 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -441,6 +441,7 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr public fun getScreenshot ()Lio/sentry/android/core/SentryScreenshotOptions; public fun getStartupCrashDurationThresholdMillis ()J public fun getTombstoneMergeTimeThresholdMillis ()J + public fun getWebViewTracing ()Lio/sentry/android/core/SentryWebViewTracingOptions; public fun isAnrEnabled ()Z public fun isAnrProfilingEnabled ()Z public fun isAnrReportInDebug ()Z @@ -629,10 +630,17 @@ public abstract interface class io/sentry/android/core/SentryUserFeedbackForm$Op } 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 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 fun (Lio/sentry/android/core/SentryAndroidOptions;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;)V 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 7de5a0c2716..da60741a4c9 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 @@ -104,6 +104,8 @@ final class ManifestMetadataReader { @ApiStatus.Experimental static final String TRACE_SAMPLING = "io.sentry.traces.trace-sampling"; 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"; @@ -545,6 +547,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/SentryAndroidOptions.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java index c135172bc5c..4c75e61a9d4 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 @@ -321,6 +321,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}. @@ -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. 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 index ad15c82ab3a..133a1c6d8b5 100644 --- 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 @@ -12,6 +12,7 @@ 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; @@ -49,6 +50,25 @@ public final class SentryWebViewTracing { 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)}. * 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/test/java/io/sentry/android/core/ManifestMetadataReaderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ManifestMetadataReaderTest.kt index 463b5d82ddb..9ae1a9b023d 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 @@ -1211,6 +1211,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 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 d580ff54cd0..a223358c1d1 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 @@ -255,6 +255,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/SentryWebViewTracingTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryWebViewTracingTest.kt index fd532c2ff65..f6bb1747426 100644 --- 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 @@ -9,6 +9,7 @@ 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 @@ -20,6 +21,7 @@ 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 @@ -367,6 +369,44 @@ class SentryWebViewTracingTest { } } + @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() From ff7a1ac0da368a07470cee75c502a9cfa9d90cce Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:35:32 +0100 Subject: [PATCH 04/51] chore(deps): bump retrofit from 2.9.0 to 3.0.0 (#6534) Bumps `retrofit` from 2.9.0 to 3.0.0. Updates `com.squareup.retrofit2:retrofit` from 2.9.0 to 3.0.0 - [Release notes](https://github.com/square/retrofit/releases) - [Changelog](https://github.com/lysine-dev/retrofit/blob/trunk/CHANGELOG.md) - [Commits](https://github.com/square/retrofit/compare/2.9.0...3.0.0) Updates `com.squareup.retrofit2:converter-gson` from 2.9.0 to 3.0.0 - [Release notes](https://github.com/square/retrofit/releases) - [Changelog](https://github.com/lysine-dev/retrofit/blob/trunk/CHANGELOG.md) - [Commits](https://github.com/square/retrofit/compare/2.9.0...3.0.0) --- updated-dependencies: - dependency-name: com.squareup.retrofit2:retrofit dependency-version: 3.0.0 dependency-type: direct:production update-type: version-update:semver-major - dependency-name: com.squareup.retrofit2:converter-gson dependency-version: 3.0.0 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 25e67951b37..3717d77fcd1 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -36,7 +36,7 @@ otelInstrumentationAlpha = "2.29.0-alpha" # check https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/dependencyManagement/build.gradle.kts#L49 for release version above to find a compatible version otelSemanticConventions = "1.42.0" otelSemanticConventionsAlpha = "1.42.0-alpha" -retrofit = "2.9.0" +retrofit = "3.0.0" room2 = "2.8.4" room3 = "3.0.0-rc01" sagp = "6.13.0" From 76d7a36a06593ac4ef5da3835233ab8cfd559ee2 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Tue, 10 Nov 2026 14:00:21 +0100 Subject: [PATCH 05/51] docs(android): Fix Javadoc that Error Prone flags in sentry-android-core (#6498) Error Prone never ran on sentry-android-core. Enabling it reports 34 Javadoc warnings, which fail the build under -Werror: - MissingSummary: turn the @return text into a "Returns ..." summary, and add summaries to Javadocs that only had block tags. - InvalidBlockTag: replace the @noinspection unused Javadoc tags with @SuppressWarnings("unused"), which IntelliJ honors too. - NotJavadoc: turn the Javadoc on methods of an anonymous class into regular comments. Co-authored-by: Claude Opus 5.5 --- .../android/core/InternalSentrySdk.java | 2 +- .../android/core/SentryAndroidOptions.java | 8 ++--- .../android/core/SentryFrameMetrics.java | 7 ++-- .../android/core/SentryFramesDelayResult.java | 6 ++-- .../core/anr/AnrCulpritIdentifier.java | 3 +- .../util/AndroidConnectionStatusProvider.java | 6 ++-- .../android/core/internal/util/Debouncer.java | 4 +-- .../core/internal/util/ScreenshotUtils.java | 6 ++-- .../util/SentryFrameMetricsCollector.java | 4 +-- .../core/performance/AppStartMetrics.java | 31 ++++++++-------- .../android/core/performance/TimeSpan.java | 36 +++++++++---------- 11 files changed, 53 insertions(+), 60 deletions(-) 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 a91225f32c1..f0dcc8121be 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() { 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 4c75e61a9d4..cabca324af5 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 @@ -851,8 +851,8 @@ public void setReportHistoricalMemoryLimiterExits( } /** - * @return true if performance-v2 is enabled. See {@link #setEnablePerformanceV2(boolean)} for - * more details. + * Returns true if performance-v2 is enabled. See {@link #setEnablePerformanceV2(boolean)} for + * more details. */ public boolean isEnablePerformanceV2() { return enablePerformanceV2; @@ -871,8 +871,8 @@ public void setEnablePerformanceV2(final boolean enablePerformanceV2) { } /** - * @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() { 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/anr/AnrCulpritIdentifier.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrCulpritIdentifier.java index 447cb106ce1..33eb71c9b5f 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 @@ -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/internal/util/AndroidConnectionStatusProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java index 62a212e6dcc..3a694c96566 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 @@ -304,7 +304,7 @@ private void updateCacheAndNotifyObservers( } } - /** + /* * Check if NetworkCapabilities change is significant for our observers. Only notify for * changes that affect connectivity status or connection type. */ @@ -334,7 +334,7 @@ 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 @@ -348,7 +348,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 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..30ce25cfc8c 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 @@ -27,8 +27,8 @@ public Debouncer( } /** - * @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(); 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 657ba54cbd2..26638222c0e 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 @@ -29,9 +29,7 @@ public 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, @@ -58,8 +56,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, 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 bc3bff9b700..b3b31f00f7f 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 @@ -413,9 +413,7 @@ private void trackCurrentWindow() { } } - /** - * @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 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 dacab11e4f4..36937550c9d 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 @@ -121,16 +121,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. @@ -145,11 +145,12 @@ public AppStartMetrics() { } /** - * @return the SDK init time span, as measured pre-performance-v2 Uses ContentProvider/Sdk init - * time as start timestamp - *

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, as measured pre-performance-v2. Uses ContentProvider/Sdk init + * time as start timestamp. + * + *

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; @@ -339,8 +340,8 @@ public long getClassLoadedUptimeMs() { } /** - * @return the app start time span if it was started and perf-2 is enabled, falls back to the sdk - * init time span otherwise + * Returns the app start time span if it was started and perf-2 is enabled, falls back to the sdk + * init time span otherwise. */ public @NotNull TimeSpan getAppStartTimeSpanWithFallback( final @NotNull SentryAndroidOptions options) { @@ -468,8 +469,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(); @@ -484,8 +485,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(); @@ -755,8 +756,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(); @@ -769,8 +770,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..113ffccd93d 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 @@ -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 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,7 +115,8 @@ 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() { @@ -127,7 +124,8 @@ public double getProjectedStopTimestampSecs() { } /** - * @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; From bcc4ebea77f5151dbfc8118f30afa5566bbfcef8 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Tue, 10 Nov 2026 14:24:15 +0100 Subject: [PATCH 06/51] ref(android)!: Mark sentry-android-core classes final (#6494) * ref(android)!: Mark sentry-android-core classes final Error Prone's Nopen check requires every class to be final, abstract or @Open. It never ran on sentry-android-core, so 42 classes were left open. None of them is subclassed except ActivityLifecycleCallbacksAdapter, which becomes abstract since it is only extended, never instantiated. The protected members of the classes that are now final become package-private, as nothing can subclass them anymore. BREAKING CHANGE: AnrV2Integration, AnrProfilingIntegration, SentryUserFeedbackForm and its Builder, WindowContentChangedCallback and several internal classes can no longer be subclassed. ActivityLifecycleCallbacksAdapter can no longer be instantiated directly. Co-Authored-By: Claude Opus 5.5 * changelog Co-Authored-By: Claude Opus 5.5 * ref(android)!: Adapt the final classes to main's deprecated feedback APIs On main, the deprecated SentryUserFeedbackDialog and its Builder still extend SentryUserFeedbackForm and its Builder, so those two stay @Open until the dialog is removed. The deprecated SentryUserFeedbackButton and SentryUserFeedbackDialog.Builder become final. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 4 ++ .../api/sentry-android-core.api | 65 ++++++++----------- .../core/AndroidContinuousProfiler.java | 2 +- .../android/core/AndroidMemoryCollector.java | 2 +- .../sentry/android/core/AndroidProfiler.java | 8 +-- .../sentry/android/core/AnrV2Integration.java | 2 +- .../io/sentry/android/core/ContextUtils.java | 4 +- .../android/core/CurrentActivityHolder.java | 2 +- .../core/NetworkBreadcrumbsIntegration.java | 2 +- .../core/PerfettoContinuousProfiler.java | 4 +- .../sentry/android/core/PerfettoProfiler.java | 2 +- .../android/core/SentryAndroidOptions.java | 2 +- .../android/core/SentryShakeDetector.java | 6 +- .../core/SentryUserFeedbackButton.java | 5 +- .../core/SentryUserFeedbackDialog.java | 2 +- .../android/core/SentryUserFeedbackForm.java | 5 ++ .../core/SpanFrameMetricsCollector.java | 4 +- .../android/core/TombstoneIntegration.java | 4 +- .../core/anr/AggregatedStackTrace.java | 2 +- .../core/anr/AnrCulpritIdentifier.java | 2 +- .../sentry/android/core/anr/AnrProfile.java | 2 +- .../android/core/anr/AnrProfileManager.java | 2 +- .../core/anr/AnrProfileRotationHelper.java | 2 +- .../core/anr/AnrProfilingIntegration.java | 8 +-- .../internal/threaddump/ThreadDumpParser.java | 2 +- .../internal/tombstone/TombstoneParser.java | 2 +- .../core/internal/util/BreadcrumbFactory.java | 2 +- .../android/core/internal/util/ClassUtil.java | 2 +- .../android/core/internal/util/Debouncer.java | 2 +- .../internal/util/FirstDrawDoneListener.java | 2 +- .../core/internal/util/NativeEventUtils.java | 2 +- .../core/internal/util/ScreenshotUtils.java | 2 +- .../ActivityLifecycleCallbacksAdapter.java | 3 +- .../ActivityLifecycleSpanHelper.java | 2 +- .../ActivityLifecycleTimeSpan.java | 2 +- .../core/performance/AppStartMetrics.java | 2 +- .../android/core/performance/TimeSpan.java | 2 +- .../WindowContentChangedCallback.java | 2 +- 38 files changed, 83 insertions(+), 89 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ddc5b5d7bf..ccadcd59b3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ ## Unreleased +### Breaking Changes + +- 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)) + ### Features - Connect Android traces with web content in a `WebView` using `SentryWebViewTracing.addTracePropagation(webView, "example.com")` ([#6395](https://github.com/getsentry/sentry-java/pull/6395)) diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index b14b6873e21..4c479759f5a 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -40,7 +40,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; @@ -100,7 +100,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 @@ -118,15 +118,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 @@ -135,7 +134,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; @@ -159,7 +158,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 @@ -270,7 +269,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; @@ -388,7 +387,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; @@ -401,7 +400,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 } @@ -578,7 +577,7 @@ public abstract interface class io/sentry/android/core/SentryShakeDetector$Liste public abstract fun onShake ()V } -public class io/sentry/android/core/SentryUserFeedbackButton : android/widget/Button { +public final class io/sentry/android/core/SentryUserFeedbackButton : android/widget/Button { public fun (Landroid/content/Context;)V public fun (Landroid/content/Context;Landroid/util/AttributeSet;)V public fun (Landroid/content/Context;Landroid/util/AttributeSet;I)V @@ -589,7 +588,7 @@ public class io/sentry/android/core/SentryUserFeedbackButton : android/widget/Bu public final class io/sentry/android/core/SentryUserFeedbackDialog : io/sentry/android/core/SentryUserFeedbackForm { } -public class io/sentry/android/core/SentryUserFeedbackDialog$Builder : io/sentry/android/core/SentryUserFeedbackForm$Builder { +public final class io/sentry/android/core/SentryUserFeedbackDialog$Builder : 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/SentryUserFeedbackDialog$OptionsConfiguration;)V @@ -641,8 +640,7 @@ public final class io/sentry/android/core/SentryWebViewTracingOptions { public fun setAllowedHosts (Ljava/util/List;)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/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 @@ -661,7 +659,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 @@ -675,7 +673,7 @@ 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; @@ -710,26 +708,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 @@ -738,7 +736,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; @@ -746,28 +744,17 @@ 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 timestampMs J @@ -803,7 +790,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 @@ -814,7 +801,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 @@ -828,7 +815,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 @@ -836,7 +823,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 @@ -903,7 +890,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 @@ -929,7 +916,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/src/main/java/io/sentry/android/core/AndroidContinuousProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidContinuousProfiler.java index 4f115ca9d7f..67720e121ae 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 @@ -45,7 +45,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; 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/AndroidProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidProfiler.java index 3f569df5378..19ea1c40659 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 @@ -32,8 +32,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; @@ -46,7 +46,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; @@ -97,7 +97,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/AnrV2Integration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java index 5e5500297f8..23bce6d1398 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; 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 60ae00f2ead..de85d715413 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"; 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..d505a862f34 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(); 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 c7f3182b97d..2259f4d4a6d 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 @@ -195,7 +195,7 @@ private Breadcrumb createBreadcrumb(String action) { } } - static class NetworkBreadcrumbConnectionDetail { + static final class NetworkBreadcrumbConnectionDetail { final int downBandwidth, upBandwidth, signalStrength; private long timestampNanos; final boolean isVpn; 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..e229744bc8a 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; @@ -568,7 +568,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..2f9522194c6 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"; 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 cabca324af5..2afb245fe38 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 @@ -1031,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/SentryShakeDetector.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryShakeDetector.java index 9f4f73d10f4..f97bbf2e72f 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 @@ -159,7 +159,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 +226,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/SentryUserFeedbackButton.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackButton.java index 589a9fa2ce6..22a010b07f9 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackButton.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackButton.java @@ -13,11 +13,8 @@ /** * @deprecated `SentryUserFeedbackButton` will be removed in the next major version */ -// temp fix for JDK 21: Constructors call overridable methods; making them final would break the -// public API. -@SuppressWarnings("this-escape") @Deprecated -public class SentryUserFeedbackButton extends Button { +public final class SentryUserFeedbackButton extends Button { private @Nullable OnClickListener delegate; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackDialog.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackDialog.java index 155464b7b73..4f1618cfdb0 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackDialog.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackDialog.java @@ -25,7 +25,7 @@ public final class SentryUserFeedbackDialog extends SentryUserFeedbackForm { * @deprecated Use {@link SentryUserFeedbackForm.Builder} instead. */ @Deprecated - public static class Builder extends SentryUserFeedbackForm.Builder { + public static final class Builder extends SentryUserFeedbackForm.Builder { /** * Creates a builder for a {@link SentryUserFeedbackDialog} that uses the default alert dialog 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 7da33575de4..2950e04b257 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 @@ -19,6 +19,7 @@ import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; +import com.jakewharton.nopen.annotation.Open; import io.sentry.Attachment; import io.sentry.Hint; import io.sentry.IScopes; @@ -39,6 +40,8 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +// Open until the deprecated SentryUserFeedbackDialog, which extends it, is removed. +@Open public class SentryUserFeedbackForm extends AlertDialog { private boolean isCancelable = false; @@ -654,6 +657,8 @@ public void show() { super.show(); } + // Open until the deprecated SentryUserFeedbackDialog.Builder, which extends it, is removed. + @Open public static class Builder { @Nullable OptionsConfiguration configuration; 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 9eb854ca0bf..2d20acbcf11 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,7 +35,7 @@ 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; 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..b2fc0221a28 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; @@ -114,7 +114,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; 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 33eb71c9b5f..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); 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..62fce10c84d 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); 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..946541acc4e 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; @@ -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/internal/threaddump/ThreadDumpParser.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/threaddump/ThreadDumpParser.java index bfb829ce1a9..e6c9430fa21 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*(.*)"); 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..4444e4981e7 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; 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 index 04cabc9430e..d0ae75f7f8a 100644 --- 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 @@ -6,7 +6,7 @@ import org.jetbrains.annotations.NotNull; @ApiStatus.Internal -public class BreadcrumbFactory { +public final class BreadcrumbFactory { public static @NotNull Breadcrumb forSession(@NotNull String state) { final Breadcrumb breadcrumb = new 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 30ce25cfc8c..1715993f4fe 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 @@ -8,7 +8,7 @@ /** A simple time-based debouncing mechanism */ @ApiStatus.Internal -public class Debouncer { +public final class Debouncer { private final long waitTimeMs; private final @NotNull ICurrentDateProvider timeProvider; 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..885ce5c2859 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; 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/ScreenshotUtils.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java index 26638222c0e..a91a8818486 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,7 +24,7 @@ import org.jetbrains.annotations.NotNull; @ApiStatus.Internal -public class ScreenshotUtils { +public final class ScreenshotUtils { private static final long CAPTURE_TIMEOUT_MS = 1000; 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 accb56db0dc..ff42e37fe7d 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 @@ -15,7 +15,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 36937550c9d..3bb58e67048 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 @@ -54,7 +54,7 @@ // public API. @SuppressWarnings("this-escape") @ApiStatus.Internal -public class AppStartMetrics extends ActivityLifecycleCallbacksAdapter { +public final class AppStartMetrics extends ActivityLifecycleCallbacksAdapter { public interface HeadlessAppStartListener { void onHeadlessAppStart(); } 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 113ffccd93d..105726e5f21 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; 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; From 349566b026c42ea50e8857fb8b3dba7fd8ba871b Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 10 Nov 2026 15:20:36 +0100 Subject: [PATCH 07/51] fix(android): Don't block callers on network status registration (JAVA-828) (#6537) AndroidConnectionStatusProvider no longer makes callers wait while it registers its network and telephony callbacks with system services. That's good because one of those callers is Sentry.init. THE PROBLEM Before this commit, AndroidConnectionStatusProvider used one lock to guard three code paths: callback registration, connection cache refreshes, and adding or removing observers. The SDK executor held that lock across ConnectivityManager.registerDefaultNetworkCallback and, on API 31+, TelephonyManager.registerTelephonyCallback. Both are calls into system services that can occasionally block for seconds. The main thread waited on the same lock in two places: Session Replay adding its observer during Sentry.init. Every captured event reading the connection type or status. If the system service registrations took a while, the main thread would stall. Scenario (1) in particular could lead to ANRs during app startup. Oof. A ROAD NOT TAKEN Any fix has to isolate the slow part (registration) so that the main thread can return quickly when reading cached network info or adding observers. The narrowest approach would be to give registration its own lock and keep a second lock for the cache and observers. But a refresh would then either hold the cache lock while querying Android, making readers wait on that query, or need a version counter that every write must remember to update. Even worse, two locks would need to document order they're taken in to avoid deadlock, which would be easy to get wrong. A BETTER APPROACH The approach we ultimately landed on was to avoid having the main thread hold a lock entirely, and instead rely on atomically publishing cached network info (see commit 2). We did so by introducing a new ConnectionSnapshot class, which is immutable and can be safely shared across threads. We stored observers in copy-on-write lists rather than having them be explicitly locked, and we confined registration to the the SDK executor (it's still defensively guarded by its own lock). Callers that need to access cached network info or register observers can now return quickly. Either of approach would have allowed as much, of course, but the benefit of introducing the snapshot it that it also: - lets us consolidate a lot of related state that the provider previously had to handle separately - avoids the pain of managing (yet another) lock - lays the groundwork for future PRs that confine refreshes to the SDK executor and let snapshots tell a lost network from capabilities that are simply unknown. Co-authored-by: Lazizbek Ergashev <20501725+lazerg@users.noreply.github.com> --- CHANGELOG.md | 1 + .../util/AndroidConnectionStatusProvider.java | 694 ++++++++----- ...ConnectionStatusProviderConcurrencyTest.kt | 916 ++++++++++++++++++ .../AndroidConnectionStatusProviderTest.kt | 44 + 4 files changed, 1430 insertions(+), 225 deletions(-) create mode 100644 sentry-android-core/src/test/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProviderConcurrencyTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index ccadcd59b3a..50319e4d8cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ ### Fixes +- Prevent the main thread from potentially hanging during app start 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)) 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 3a694c96566..fe7db65c621 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,16 +193,18 @@ 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; - if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.M) { - capabilities[1] = NetworkCapabilities.NET_CAPABILITY_VALIDATED; - } + this.capabilityIds = + buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.M + ? new int[] { + NetworkCapabilities.NET_CAPABILITY_INTERNET, + NetworkCapabilities.NET_CAPABILITY_VALIDATED + } + : new int[] {NetworkCapabilities.NET_CAPABILITY_INTERNET}; // Register network callback immediately for caching //noinspection Convert2MethodRef @@ -144,10 +247,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; } @@ -162,9 +269,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); } @@ -175,15 +287,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); } @@ -192,6 +298,10 @@ private boolean isNetworkEffectivelyConnected( } private void ensureNetworkCallbackRegistered() { + if (closed) { + return; + } + if (!ContextUtils.isForegroundImportance()) { return; } @@ -200,8 +310,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; } @@ -209,16 +322,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 = snapshot.get(); + } 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); } } } @@ -228,79 +341,75 @@ 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(snapshot.get().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(snapshot.get().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 = snapshot.get(); + 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); } } @@ -308,19 +417,14 @@ private void updateCacheAndNotifyObservers( * 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; @@ -338,9 +442,8 @@ private boolean isSignificantChange(@Nullable NetworkCapabilities newCapabilitie 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; } } @@ -362,121 +465,147 @@ 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({"NewApi", "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; - } + /** The current snapshot, refreshed first if it's stale. */ + private @NotNull ConnectionSnapshot freshSnapshot() { + final @NotNull ConnectionSnapshot current = snapshot.get(); + return current.isFresh() ? current : refresh(current); + } - if (buildInfoProvider.getSdkInfoVersion() < Build.VERSION_CODES.M) { - cachedNetworkCapabilities = null; - cacheFreshUntil = Deadline.after(ticker, CACHE_TTL_MINUTES, TimeUnit.MINUTES); - return; - } + /** + * 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 = snapshot.get(); + if (current.isFresh()) { + return current; + } + } - // 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); + // 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; + } + /** + * 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., below API 23, without + * permission, without an active network, or when the query fails) + */ + @SuppressLint({"NewApi", "MissingPermission"}) + private @Nullable NetworkCapabilities queryActiveNetworkCapabilities() { + try { + if (!Permissions.hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE)) { 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); + .log(SentryLevel.INFO, "No permission (ACCESS_NETWORK_STATE) to check network status."); + return null; + } + + if (buildInfoProvider.getSdkInfoVersion() < Build.VERSION_CODES.M) { + return null; } - } - } - private boolean isCacheValid() { - return !cacheFreshUntil.hasPassed(); + 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; @@ -484,10 +613,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"); } @@ -495,12 +621,12 @@ private void unregisterNetworkCallback(final boolean clearObservers) { /** Clean up resources - should be called when the provider is no longer needed */ @Override public void close() { + closed = true; + submitSafe( () -> { unregisterNetworkCallback(/* clearObservers= */ true); - try (final @NotNull ISentryLifecycleToken ignored = childCallbacksLock.acquire()) { - childCallbacks.clear(); - } + childCallbacks.clear(); try (final @NotNull ISentryLifecycleToken ignored = connectivityManagerLock.acquire()) { connectivityManager = null; } @@ -508,66 +634,72 @@ public void close() { }); } + /** + * 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( () -> { + // 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; + } + // proactively update cache and notify observers on foreground to ensure connectivity // state is not stale - updateCache(null); - - final @NotNull ConnectionStatus status = getConnectionStatusFromCache(); + final @NotNull ConnectionStatus status = statusOf(refresh(snapshot.get())); 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); - } + onAvailableForwarded.set(false); + 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); - } + 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 + // 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 + // 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 snapshot.get().capabilities; } /** @@ -768,16 +900,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"}) @@ -847,6 +975,122 @@ 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); + } + } + } + private void submitSafe(@NotNull Runnable r) { try { options.getExecutorService().submit(r); 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..d201d48d111 --- /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.S]) +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 56a2a12928c..56cf8f4e0ba 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 @@ -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 From f80997a99561439627e582deba574be11f95a97f Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Tue, 10 Nov 2026 16:56:02 +0100 Subject: [PATCH 08/51] build: Upgrade Gradle to 9.9.0 (#6539) The wrapper jar was regenerated by the 9.9.0 wrapper task and matches the official 9.9.0 wrapper checksum. Co-authored-by: Claude Opus 5.5 --- gradle/wrapper/gradle-wrapper.jar | Bin 48749 -> 49154 bytes gradle/wrapper/gradle-wrapper.properties | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 9fa7f288283f81eec4952784c271abd7e0938dee..51cbd2a6f8121b2ce12daf979b128058fb9672ee 100644 GIT binary patch delta 39790 zcmYg%V|yLo7HpEncCusJwsvgWwyoXR+_9|&O=CB)lxq^z6teRgD$Ks5ykO5?*EEi)6wxrCRNDS9(VwK$%2M+H-&>Ir zcG5zZ8wj?qMv$|YPmYgtH>%9z!|qI46ang1Jgcw@`5klC?2Xss=(s~CP;sivvdnQ4 zxbAsH^i{MET+LZgZ(WCJYydKwkFyt%>Uc9Vsop(pTY5)%>vLI)B|j!OhKVIu*rqvL@LRItRcKO-|(oH7+ArEWvp zjctpq)WjI^P2d^iAT1D}4<|i+Hc+q1*SAYXWDjO<@m^~&5OVMfKZrjOOop1`WD!_7 zPxF4yyyXA34*vZ8M*Ncr7k}s1FJZ=>`I@aYjKu0`2Wcfn+eioA^5HM%0#cjYFw4Sb z2-ipgj;?(mTdwfN!!}2g+y=KvJeWE?){SnxG>p;ay%s%X-3HGE69+w99PfxzEJhr8 z4G#@YkBv@ej8*2VHW~8=!V4h|##|6c>w4Ls)iv~KRVj5MO+^ov`T8AN zE_Z-e2yn+{xrv_s6Rez1Hr{#Knv=_6%SJ^aD+7xr$F^Fbn-TmydDk@h_@0o#KSfSl zJOg`Hsoaz-LflfzlRR6JmWAyxFV?wzL6dC&-DKClv+MwKLC$c<3a6UwVyG&%;BbVU z;H4Sl#*a?Ypf3?JGDkhg`SkK?W)BH+&a{@Ue(-|AaYnnN|@*fDPv^IV<2tEdgE+2+eploWnU{# zE^Mz`d*e|{WByG-%POMEdHwQ7ZDf;$P68a6Z+UW^?=dUvaXQnmy9Tm{QR7} zfGZuJPE5{dbj)HdwahBmY#}CDD`4s>pdM=or)+1n^~im<@-WCE7WE9W=olt8NsD*x zy1I7;tzUZxVRyHTA$+T$y{nsZ8*5}tQ>i_wVqszy(&rFK3}HVbG_F#-+wz76u50{~ zH*lN8z*%f${8n)3Znx}2Z|r)E#ND=l7_NWw{P>#y6S=&YeEtWevr9>pzj1*AtCCl3&)Vh?`dpLP?@J~maG}_IF)p=S(fK-V~u129LZ7B zteIt>SC$4o!&XMZkRMiE8N23Lw@0A%I>>g&6dRm^23bkp8Wzu?QDCX@Wa8t_xJN%h z1z?EG38=trcwv{KCf9J5)vwhlty1rIU&b>FyL@Z@h}<*??a)4+jC=ECSVvRPGXgmf z)Y(Vpg})Amu6G2pZ%cYtdRsDOpw!e64@`Z2@x)89iT3zAz5(Iacs4ebSh z`Ry?SpF?!FO3$7l!I+CO&Og2udR<_|Zf3qP1Rq6=l`AosC3yHKQ$#@J zfv&DG*b+B0@$S4AEqYkA^u>xjVsbPa5HXn&)h{Z;^y!ZgHG zIMuUQyb8F*96T7t3kSlwY!;O8{!!Q~0|5R(`wxRroil%t`3I+5@IECmSQu9kq_L=r z9n3;T-&lpc>*M8crEg1Eb5Eff2#Jl2)E>vGF$y^4>2ad8TaZ(Cv$4ruFKpa>f%`6q z$mwnUl*{>9<)xBZB9`)MRS7P8**eX8-|{H*xE=-Vett297G?j_+xz+O+903e@NIyJ z9vrK!%@J$8e9_r&w9T=cqlIY+YKtImr?mYsL9F!+(P`OkiOA~56pD;xn!i-tU1!ZZ zI}4IA$$ogtXxqmm${^XGf|($8I`Sc~6gXHq;ex>i>o;t_mXo!J($8kSp6)n&LJhR! z2F}jtw-E3u_-$jOwf}+_WT%|SP_o^0(;*mM=?-U!bSUnf^l~v+bl7qR>1i8YBO+`g zZ#!%GU}gf+0(G;9iYq-ed|cS3(832_C;~m~;8=KH`C{Sy{axYb=`4vd$oJua4OW=I zO%z{FA>y&VJyyS!J!|T&gN;tT@fHJEAbksFBPCoj?Gs^7s20@_e(LVXX=7XEA;+6r zC^<=Me7FX(3^Rz?<|GqD1`hF*1d$Ugc@z* z28}4nn5Z$+)wi@!qKa-IH8j8ZE)0K! zx;l0KcZ)~0q_i_wi_y3447tAoKmWZq)CAOXa-w883}w4Ty!q<`^L;`>8Ry$dyUPA= zuJHvw4_#sxrFQLWVm=2_Pu=dh{Y?(vr)bh%WU+BY_dxy=yeNM{bg`~c5m9X{C8D3Qbwik!kdCYByzjr|OLA`k%jNl%0}c@dW~64h{lBRpARX zHUvC8JUFNV1N=!z4Hh5}0+m3m{E)3KT5FbyTQbF|7^ zINSD73YAqzcch^Dgli1$>+)Gyd*sv$c)_N&zd3tI+> z2Wy-kbonx4Y?ciTJ=j+~ynMstTeSo1{<<2k+L^~2@Dwjd23(G;O!7wF)WBH4Kj-=} z4*S>%*t8Ecb2tGMlrFoO%N?AIta-i>oQGTA3fEY9I5@SLB@zbl_s`~@`)Ecfz_S_h z+??<~Gn*$X`E>3!g19IL=Q8*dh+GD(Bc(_nfUlrd|9~-nw~MJGB7-f;1uH^3g#_j? zj^-Jax+(sCN5$obEoCqJ3RO#xT!KLyNF z`58gT%hSy7mP;0T=$ILtTvPiQ;SZs@F~=Mk6q->4d90^x;WG&U#|#Fg z)CguCqqNzC^x|1F$8RQHqDbQD0{c#T%Zx614MF|{I~6`ap` zjgw2pe0+ug7x}>Vqp1TC4F!d0cIaoCm#egShWGAdD>NvR(U=T|6q#bz% zx?zeiJ>AEC;qHvx?_MYQHRj--V}L0D*bqdCu<@7)S65dD=r~c^WLxOxRHmCPs{a{? zyYvh{Sgu{rjH}lR&ZPK7voS;FZHk9bdE&lA132&i$!RujR!XCq#BDS&iA7%2Ywwg{i7<=~LB6EBXTVv5>y~)|MswvY_lHWLLHP1>ss46v7 zO8}flpDLwUm#k<_o*zdM$HIq|tqVpBIX|mvZ^etJ;Iy$h=I|o;|K$ z&Wc`wW*%;=$x2FL-Oz!O+=KZJT3uWQ2af@5ZdO5p!m!}I3_y9FcP4qjM7Ey$# zvw?GNyaFcysd72MY92;;ym6E+MQS_=|9n~W3SI5Qv)a5QwQ6Ne>BX;yk8ZET$DBSr z9c=eu@!sNi_IS9IQ8RmiR&T*fx2`h^MmIRnAhit~#eTg2QUC99?UQGh2Cv=0xq0v^ zaf1F-e0wX$40Evd{f>-Q3ICQlF?h*9tp@WYeEU=A_bmhob{c6(bCqG{Ej+bg&{gzQ z<{dsP-k};1H3%gq%P1fiE%^?*0NYzdjgKQEdltpEWS%DtqX?V${B+Q2n>4>R-dz7x^CN}sl#SW!|3xlvl&_YwNN$p|~`dLYmP^5>HYrw-gx$`fr zsG-U&e$C42c@pl^UP?(NlMY_5PC+XJxbF^BN7uw@CDrd>cL_8n)Qh{&nec2zG9w_ z=9LGpIlmZ<{k`Jr8J_N6l2)m>HBaPX*&kwGr96?b8-F!vtQAmwTi&kxPRWlC&94f2 z0=tuPLB4`3N!hTA`9ro<6PaO@DO5l1kW;C~B3lE%m!yUu1Els`l5eQ6beTc=PcH>O zOTf0((W@UGQp;cb+i9PvNo+Kg6VwQVr*D~`f}oP(i1_(GnxZ}eF<7ZfdaWohpO|y~ zqb(b5Z=XV-cBo1*w;s{%0PTrlkT+bgv3zchZDb`o_RXk% z`R_l0fP+VJbkNB&xyB?qbq_t$*Dmi=HuRZ zr$I>`fq&j-XH6gos@MW|HUqZ*RQa?wQd;Vm%qJ8W&!dczWZ}Lj$!I%OGTLtAWb73b zC2ekfBiI~RyNhhCYM6FGAEHSTEwou)ind2TpTEs*~BWeSg+;nw2#B`cvKXH$?c3ib8(i^+2VqFg?EIuf%@8UxX z23|aGio8UG(nn4-ZiJDmQ{iJOpAF2}5`Pnh_Z>4!e@s%edrJb4;LezJhyD}Ut^Td23S|L&_V|F*ZIcfdj#oGlnBJS1C{r>40&X4 z`|SkIrpCiwTT8AmI$>0o$ef9WK1Z)@g-R0_=L6xJW#&X15^n_8rtHyvnW&UoAG*H{ zy#W;~XWDF2ut=A{E=tfAZ?^@4<@p*;XKuW;CJa|@MMo^)LgBH3QW`~7;U;*`@V6kx zJGoJXh`0rlrgci(>+fiti4G*nsUUu+CiIGU$y=g>rLUgngdCJx3_8;7A2|KsVJKWm zCQ`o&s9GTjvv};{4kdnGg1!+DQZsKW+8>zOG5NNdg(3?lOKC@zU&Oi!1QpXS73{C6WN_6Ow z*lhb&QOAPaVHTIA527DdGLE_APL%79Tg?0Je!bAE%Z-dl1aF7Mh;V|*8B+~-0^`N^ z_vzKkD|IjYv+V{M<(6{yq2#GK#k4w;72|ah`fWo3nXSnd>#>CT7hf{*Qk9|vCBy}R zwdHp>amtY_zeK~ul}sqB`jJq$;*j%a>YbC6cD_2hpO$2Lf)so*0LD=Ug9cqm-AF%^ zSV#q2}k_?oXc)AFiY=n z((U62VyZ~?v@3b9k|RbUn7c=HI>WJrii=+Fv1rvhT1~7_|DMbpGoaa8L##aCeliz3#j?ljfkN7L~tjZNmQ=D{@ShDuAS`| ztYV9*Me~)7B3P(j(!)|In=U#f_saiTiKhuH*JHG)r*iD>KnRH3kGw6Tivdndx`j8> z4MC@h46*x_-#)=(3t8M|gg4o{=Ki=sk|8LmMTjva0C5H@?(+k?tr|6??)6==>P!>O zy6vc3NZKKA|75{=RRyJ!Z~^DEtZJ-{$B1SLLko=Il*r~HlLf=YRK|!kQhk4p_2#bN zc@l~X%6;7%diH+A?)P{cQJ(*ca*a0t0n7RoExIPbn|edgGcv&BZ0x(D1MRPC(t#kT z<$k*ZPtkr0tWDZ8(SF}YOmU$( zVU3(ni=xo~Kx}qx+yh3Xbp^H5X>GoFJz@%JHcB@~EW{Rt`qF9D`rh&=Rl0dKA>=Ay zNcI;V$=&Xu-O9v(qtBGK2B&5={akit-bXJ9A-K$>el8v!`n~S}N_-Ujk35N7t{er7 z@g>!Z(~F&<_oMN7%it{zMjhe_cewr9+%SifZQ>a!lxXh>A*E5W?LdxLiMeAv6(7^2 zwDRn1Oy`k`b;xM^;j_ z{>3F<7liXAE+aM>PqnKbp%by?rU2DttVxOvp6*JH`B(2(!=Mj$RCzXyNQyKVO^Ink zi+4{Ow0Kt2uHKz@k4I2LvC%WJeFY7q9pm2jop(33@6z^t?=Hi!D$me|q*|>(=_uyb zWn=fD_cGlYkjt87h0s6_JU-1K#;lWuavK84H;qIE!#a0d`p!G3rrAJ@?^BJ*{h@Xq zY-s1OjH=V_D7ZhmvktbvhkP&{D*xdRH0@qguYbuV|G#WN6-A% zzQ+g*zArA~O}FVs5snU=+i&K~FWTqqZxq_U;OGrDy6767Pq6@vy5^w z`>S{40Q`##9Z1p*O6PC5s1%py55Uk$a0z-rMe@nwmr+KN^5OseOL&~DIlO0z&*8~UyJ{sX*;Bcv^1X$7Egf3N z=_@iNc}HL7LBw%6uRm|`8Qkab7XQrmNrga&RNdcnVrwy@0Yw^ zVWv0(H+Mljk5Y9WK|1Y`owXMzEmaoL7!&uHebL zWzaEfTacP&uJ!o-bSjS96w;3Fo+e|a@@+zflZL5^Y@sgwcTHm^QA5o>)UWJiHO2}T z2OU;Ok)s7%+#2qKxH--S8#$+ZTigs8jK*%~Nc`_B+g?3M*V3GtzC_<(h0x`O03?s$ zCSNaYWM7LXRqG$A&O+wqC|7+&vZS;)A}~yr?3-AB`W&GK+t>cNTvORx3g7+@ zExT5teOQdZxPbzNcn)2>!q8<`qKA$@R;O9_h75Ka6zGT*?CB+myrs8#Z8mtw$DoA- zYkwtng!EQPgOopIEwgOiTb($%t*s2ye+?V|m`e3CU85eLUb9=W(#cZbeNseXs}EU8 zUr4nw%i=gSqD;HjoZRf5w@&9xp#K~82i*mXBDQ@C&xlDYyT0w=XB1`HP7AxAD+8la z1n>wA%YX-JSVBDd?ICzvCuV{TRC0S&w@AOw}wU}FyXZcQSWUrkj^cF(OPK^D(?ClG4^L@A8RiEPHWm zVPq)PTAtnT?<@ugx$nY_?2+<*%V1!!?=*$a)n?ag_7%sI(^^fnYcf2MHk0HW!f$gl zqrc_2>K(qhEt^R&=MW51s7eg|g$$}&Z;aV@q$!k3Ks_E+$HD^Ya3B|B;2C;x3ERb# zWT_;&jbdc5%hIBHK0?qj>w%~7MeVkl79VoA7LwF_84*do($$Vc2=bZWeH^+PII%GwhPaU4$!MYDfMP4BC?euAs;ht^L^2y}&SE zEyUArImXFDcvUuwTWpH7Q%Di6J(&AdXn1Y1+rM@df|1R#7)BX!a&TN6!xD_?PbcwH zuuGBgO3j?3I_6#LCd!Lh!!sEPPW;P2$oAE3ndl#Dyl^)o|;{S{FmnWs#a=yw7)8=bP>;bk$A+yYewp?J6h zFzmo-T{5zS*cByz-Toy)8$It1%|agigOf~Lp&az3YQpUn3ovVV z2E-G$Kk{W2HUF@==90JH^+37T&$Urep5#N+*lt3?`QUfM0#;Vt`A;EE8p+%W7xTVp zBCPa{*X^o*YtejhH9?JpJK|8y(dHie7#JveV#6moK zL5UyaE+{gEV&UEW7Tk}b{o{ognIjt9WhAA)9nb`MWge{TX}O4g5B+F(cWNlv z<9k_wD{PI?-}+nBhaZ*bkKqH_j9aK&T%`YzqKuW;Ru zHonDfJJS^?N;7KXW;Ptz*)Q3CC;1;wH>APPZ1J?nCc;4iqR)KI6gE8V_2DDH>}6H1 zGV9is&Z6$Sh7hf@Q zGhQ*APEVN$_M)!7FbvJyKkDqJ9_7}X9XZur@f*pQ`{_C`hO`7)IhqM|s`1a**IaO8 zTC2hBV>WPTa{puiI_w^3?eIOPQ)t6Aox{bV^dQH#TPSFBo7aR*%l`l51&9QH}{8A7Sx>>%#mRIM-Ays zkxt&yD0Ouh(c`XI@t*-vrSp^}bI>&L6}L1u9v5 z^RtgO4Ep!PS2l(m#tx7D(Jb3(wjDtp@p7{iu_3>Em;rv!iU~^7hI&(mLpzIZK;gf* zgUwN-n9&DC%cfnO9|4OI7e#%ffP*XH0DiO4ky;G;bSk%XJhX;BZ$tQau$hkec4Khg zT&fhwy$R3;t>!gvN_joUH}PA@$TdFt4X@x(zHSRXyyXAN@Ch#aAg_KsDduq9lK4pwKpt(;rLqgodx=T&509tqEK zCaSzwMFTnr;T&txUZg)tK56va7%hEuOUrl}YwAJAAZ(*XP5E>^Ok|sPCtOW%C9<&8 z#w|}K+fvBXGp}RngcUM7C-Zs!g&TQ&3#v=;eLlHa*0ar7Y%P_0J*qrq zR#MR362`{j_!m#fUYS#j8N?5w^KBgeS&SJZVad1QphsHDD16IT*j3q%fm_T$8GNN# zlD%!=crcJb+nw%{B(Z}e#_fhgpsRa6DDeAZ_v@%ncrj|y`T7?X41^^NmY59UPYKll zx@sx?k%JqBx0jR$iu7cfbt;x*gPGMO2sF_6`YlGqA}3t?z7o*^&!FSdu!vUzp4;%6~=-p zONAL6SQz>*Y?8OXoW%V8x05xqXT}*Y!9?QhD-!7r2zS&kGf5OetUB%{bguYfE2@U? zA@2yuNFnA|MMVoj?aUPwufv%}(LMq}#uZqeC1S2dtyK>$)PrjkHQ>&TsIsvP;Aa23 z*aUA6W1U0)n-3BGUrr7FBcKdYQWzA&&TDD0vuHN)e@YIswIk@qmB$f>X2oSdlt|i~ zZr%0AVr?qMSGpLfk5t z9C2Q>a%)FVrJ+ddWB2hyZ!+$1okHExP3r zG+ca6Cuz{5G#<(4Y63kC@>ldmgXlxi*U;Q*@cS@Qv51E44^*&Gs9v(MKZ&(+;8xx6 z7wFF7qS0`3rK0BuE^U;-P4)D}K|90@et*L07VvG@&o0T>zu`6p@9V?P{9jA z0w6MM`QNJWMf1(3UzSW;ww#?)%X7D_d=}L)(EDz|I#D8bBi{}b8N8(fJ(uuy1D61w zh&EgWU3LoeUL#REJHn)W9@qSR9`_HTyMG}}Nu4>jx`Tthzt}sb5n2qe48564vuDHu zl!v*QNwN~RwcHRxj|#p+zrfH>ZryN941n+-zTt?j=p1FRrn0v!Y3(~_0?e;)yW5k% zb*qA>Cbjyw2qXVmXAB7bT>+gh&qMXqrpPII8c)b>6V1@T%)@kb>Lfg-6pmkFzC3N} zQtIV1w?%;~hnV38cG+RK*i06-eM6&u69?Y(UjC1%Y)~+a@Z4ZRzyxw0pKzLmDF_e0 zM1&O)f#WA5wyliN`x+~rZ-tRS^QGN9)-6hQC|#KO8!e+V+xQ&Ot`~W1x-O15;YO+I z{6gsQ9G!h(YzuPD{u(5&Q=!?zK+!qJi~E7Q)>?3e<|m#J<}8PUH<{I0C|4Tp-T;wA!jrd|)oC;q~3mJ4;0lMVULI0+)X8tD;KZ zftGf0Zaq?!%FHTpY`3dac1&bO)ZA78(MOW!j7*B8PPl8=IG3ws2lW+Gm6F`_ORA}l zMN)H6h?!DV18haQz=>ZVhr`>_ND%VIVj|-6BBcUFa)P3umLPm?a!d&x9LT^8A_#f% zAX}Ovit?-|xh1W*2tHp!oboCba`?mc0-@zhU%x zqF@+GWJ26ZzixYd7=GV8vqS!XDQ_A_qgLs{Q{BS)foM~%BM2WO#F;q^lTf`T)5k{& z`Gr!Zq!4%(`Q0@Q1d<2&<=F3GF#P(DWBCk@8$^E{itr*mt(qs1^Fe}Mi>pqwa~&+1 z;WNUej)_S55`N&$!*iB-<+d1SO%>75SVa|KN8P3-u`5B9BiBF9cBKasU;~Q1uw28Rvv zB7Fc3xKS((vH&bCP7T7J_KCNRu!|;`B4AOnh<9%YkKG@NJ_#pqkwrQJ5NMJ{9{&!V zF>9{oyFe&NEZOk*k>&&3` zH!S?-Ceg{xAJ+d+4Ps}*D&jvY%LD&kE6XUM3`)@6^uW@>|C`Ta2Fy_>a7K|p5vNkh zg+0>Nkd*I8P1}t2 z4ai*j%+Mq+46KdkxxD1|+-9+x24|4h?ge(viw#IVuULcW~%W4q;mGSE)x?>QA0) z!dn9D-#UJn&5dBUDGbRI3U9x6zFfr_K7_Ep%GCX+yF2Xc2lz7!7LIM&uk0agd$v2( zNK?qjAPg?hcySi;c}sClPzT8~JlYYkg3^_%D{@X-q0k055WM7-@EOQeY-rj~=yZp_ zUlciC%#cTp*p7BU1nT~Zf)WKfi06;r1`jgaHCg2gjvxh7DO;L3Vp(Ef=r+nK4WTEoz_F~>aCHtS3-2Gv4f75T94%-?14WsA1l#`MGkxp^DaQY7$Sb@N4-|b*3I8RsXfB ze}Qp+*;5ilCF>|#m9ddWWu@bjUFXzVBv_PMuiAwB!WZ85;foa2gAQVr0ip7Se*ESf zT*-XS3$;LYYDr6~vR+|mKRjvOj3EfQRUy<-0uxdL#QWY$_NWF=(#h!wtYLu2D9_Dk zm4EQjsUI}@w9)~s%b8Bp!Scg^Je(TJrJ6)xN?E{$NfqskoE`GbD?7Y>21L%s?ZGy6 zHW6W^fHh9HOqdY|AFH|zNE%Mc#c1d~*zhNu!b$GlN^@?*WcU(Yz-*F&m+6-=F^2)S zxiq?EM((e9?Xl`(tLoI;(i0UxnA)y?>oFQNjc-@sb%twjv7QQ#N0YSQ$fQRtWy9&I zI$N9e?X-O0v1jzWvsPIaz6a1p5Hm8pG09zFdm`bKvTFQ5wwIds13|7`H*1)<=-Q1P zKc;_V{nTUzYKDL-FH717zJJ?gAYA`$$8Y9iIw0j|7SXiapPe!jvuW%PoC%~FAe({R zUvD|B&$4$nDTpQv-KPOM!t`k{F8v^wqNT{%)LagJOH`9q?;MYsj6iN1g^s=6RErWR zs9Y)ulwsrsQ$)qnfD{8QZF_(&267y!J8MKa*YjTnZJO&-H{(s0qP5OG8Jek|;intn z;5nuSJU&UB{Nb14pB^9iA#>)x%ObhaH_KG;nwCz^-{P>ppOFb9wR-wjHH9)i*sAy# z=L~+sacnTP`5u;m*m;s%G>G`j^%))XG9OTY(o}XT^0sm)3nKS@O!WUbnJO>q7vFes zB7L*EdoUyfyKr8HNtB3jdX6Z)D5nB*x;U6LPogd{lw4uLSg_TRq|kJW7Lm5EcjksE zXXSmjGsnadnIx(TSHTq76fFd-NXuauuy--QJ+V{M4PI2iyXZ9Ci-rR47oZoaTBd?c%uaQ4;2CCBR za{S3zDOs%w1P&BZVX(`Y4kOdr>~QV{w}yeKK6hb5I=5mIQLkDPw68`JqPLl8phHr6 zLQ6GJ|AkcE*ODTo&qPLiRkky=F;b=yl{B0s^DuLO4tlu`UiI43Yg!yBx-V%rCJSH9 zp7cg-CGKcyK-^LNt|!jQc!6_(|G(Pc{Q|;;_aCTDnhe1Dn#0%>r2PnXM0!Tk939Z{ zf8}4`*W0e%fBYVd_+Ne(MMDEWx3Pl1N+N>3%S97}#;)ROAejN9R|uubabk05LUHC` z9o*LQeok2PI`c5-JN=s8xyd|#-MSlwyRe-Ta0)8n{P20R9Hsx5q4_FyHb$NIU<5jS z3EJiV^K{eD_hl`D6i{!} zF({qF+(Pben((8pXB@HZb~$3waY6ubBa>{Fak7W2KU@TFF2v6VAv4OPg;t>Awx_fG zpaD(?PtRQ`N1lwSKa{6tU?JDbPR2mkH!h$de1p0jI1PjAhxl`>6>XO8q(pS`%sxrA z_6$9^rxC%bkk@1r7s+seE~=?_{Loo~S$RpZy{$#`MK=kA63k_K z=m<}1H=&7>udp_?C$h83%O-PxrGFm;JNxz>CIPvnHJgJ~)v8JgKZio0?i&r-A%99B zA#l*#Nk?swb1QXDa+Ho2n2U!I*`kHdgeUP_3Q(&lx5cC!ME_>pDXBRw>1u9^MSg&s zOR2Tyzu+3h78ug+kZVOfm?H~X=DZ$oHtUKqTl}l3B_Zg=1i4Ck@;jiU6mPFS8tUw4 zuYPy*ho|*2m*%kXQP)-WcpDZg!nKKYl}_w)mYrQ@UWn)bjsTUGMcXUJ6&4<^0Frg)5$ow%CV)c zggTF&=!r7MII=D=y*S&=OR*7gt74E&TDp;A`&f7zb~JjpKLj{9bTYDp`5sFwC7c*c zYW&5kHS@ct(pvY=TSZI1%nS`9$h@C&{p**=mzh8&v*?im!Q7CJ9bG*BWvv!Om%V1v z%3GQ+A=0}&+5T4SW!y5*i$h2E3|5EXytcIG^^({?wiKRLIb}_A0w;hnm`>G3P4F!Y zrt@9$!=GuAYKg10QS!LJ=}2N_p3n9+&M$U=GvVS-`ljx890TOTvl27IWc3HixTYoK zKZYrJ8SKOi54&}YFdWq;Y~qQ@bR4F!ggmpVyeew^5I9@@_B4?os5!HDHL;W*3yeG~ zO5E<(chK7&5_{M+u?`ep5ezZwGZBs#bk2U@>Da<7&&ld`=cN~t}_H&9_}1sn^AV4jd7v1B&AYU&0`lYNV? z4`;0+k@QJbVd||1oz$l_+v=(LHbQ7nv{ZU8 zRwP`;G-=^RIPWil0}RW?vY_C25SH^Q^J*Qxe4y*9@BoiL65TM2VQrahi9|Fu;W3w# zd@5+-fw0VTgZibb^yB4rg}Kt#>mY^k{kuNY75O^IOYb%n(TKT;2gT%!m?A;&ptRVB z*e$5@Ma35|?lTlhOdXhY-Oc{cHl}^Ep*}!Mag6(tjVW@2!{pt5jDOeOpI~ot17KbR68fjx%i&Jok{Gp1awb#n!FdJKEE|e9Fh_ z8xX5e$MkvO0@tea(}O(7oVtjQU)axX!#5qmLUv_KjAyv}-x|7vQ7|I$h}i%e%4!{E zQcXf&i$y4P>mj_`>bJap0@*?v#jn^)bmnwhd~^JuiNc4_>3n6g>N`!Y^vHZ<5T%Gq z9FCpZH=74;Sjwg~R?l#TS|*(aD?HH4a`g7Op~W0;rmZaI0!9r{RXroK6w^EB=HvNX zqhO3#{GVc)8T)_dPOTjcHOdOLEG>XYj%7zJ8N~P0wYU#t3lQ%%GE)~${tek+kzEb~ zk@=e6wmTE|q$^pI7Vx<^(TzwBWR5HY@cu16ctcxqanYKSbSTLsqBJz0nvV+%7Cc~{ zQ*o0t+tcK_+u~X9$uQXZaJwt3oQ;hTasap_Zrqla*)c5q>}jup$&PXo zC6Eg$%Q5&^{VHjR$`8%sP0W3NBuxB`7;?xj94X*&+fmqN9^9U~+NV_jrFh_;hc(f6n7MO>SqPO+ab-Pv+HN^m)-H&!CqKmvj z9%$`M0rIsa){#itVRbZZEy&?qRr@W8<(@SnY&dFV_-ho?`ppgZIJnldniSv+&cTN5 zrKmK!@ySc1a`>1c>p?ZWh5HZwS$b^wPyTgarvK%f|2y6QUr=I$DV0S)lk$|}*uux( zENDayJhoa{Fy$(7a6(a8unqZ<@m(k{c&7Z<9Vp$~n|GFJYo8dk{2B%H6Xlc4? zLshFU(&{D$uwl3b2u|2rfgg)60wh4rmY-P3(L0g{I(r+4(b0pdMOoBp9;> z0|8CC==kfW%f+#3EVOJhCOku9PQU+*w=tBO5*Y;z4GF8Ng0uVyXMY4{%{xqKl79Eq zftM7&+xu_!OvMb3ckTBtABBPXzo7*hcvb@gEZ@NbO3*NJ+0?`jp1~YVaNG2BYIR=5 zwO>goQ_|4gjIa(%NR&J0h|Q_ipel2_$m4S+79`sIMKweN{Vjy+)-L2r|p%D~t|B(cN+cC)H;(x{ffPA>d0FA=TWX8V%jsmQvQ$ z3n1A|5KbcMl88)8Cu;d!{u@bQFI2=}93h|K|MSU?xCA3g_`XVZepob->E5a2yMEerICpfYIswga^Ja6g4i4p@ z>8W&{)F`u~;T-4ts>(y;^oxfs#0}dt0vbf$?VoyzjD456zK7L8*QAWjQVUPS#HWBq zqw8Vw9t9CD>W9*)5y;0*!=hm}|#J?Lz?5LX|4-RGZ zc!1F`2`!*kW2&+3B>C+uVsFC*OLC9chbg4byCqhb7LFiCCVwT79==|Q(5#7ol*^vk zf72m!%G*R*#_q5$&o%wr9nU5IZAJdR=Mbp=iAozRC1`Ubu=s-X5{97oD=@v&1O5`7 zlYg*l(Sg+gO^tHP()b;A+1;2jh@yem{29XK*gB)7P;J}+PPbcWxNrD2fmGEYleF|x z!|bgeh|KtUHyPej7u(|UC)BY+i7n{s3(5SH2450S299`4cl2e9;h;2yfhU6>@{PtK zSoSZ%lM*NKq)PH~art5?XwG=4os#PcK;RKMw>iF7ZRt|o_us-Fswt-Wpn;qv4;~TCS^$Upmf&0SyC=uCFiwti4#WAK=#q> z+I_}ns^b!Lau!U*u^=_~|xX7ek-7?D?WXmgLE|gvYRBrh%{dmYtsE)p37@ zu1l6<`4i;HXwpq_uN>%O4;jKn?4bq~nhFI`4H0yAqZ2zA4wQsH$31V!m4&A8R42or z5u5p&+x8%e-bWsC;(1MYl=S`ODs{nVHf$+ss0BH$VHb7>IqhK>`X37g`xrXsa`ztP z8BYFhkOMf_jr};(lC0&F9^__7)SQ1TNeF)gM}wpW7_?@Mg5wN5LBpi$yQXV1?A|oC zxl>Bd`;xqpgFy_b&~bucU%U2N&9V!EUiXv=15tXtfF(|WA!%%NwblEEJq3wlIB=05 z3Z|+7wH|mvMv!8N`0hGb!|5Os17{ebEwoW^j%Y!(P#c@$-dlJoOur@WhDd+I2rl%{ z=v}0qwP&SZl%aP$jZLORKYG6n;LeaKX|w)GSAZN2E$@G;%=?7Amn|%5KL%v-lrc1b)a!4i%v2C z7@cS;=oF%}iXK|;&`qa%h<1N9o?k`p@F(=WZ=k1X?V>%@u%x&f_&4Z4n06VjWA6tX zev4u}U&paJvGpVR)?nm^pR6KQN3uUnOC4uFBNM_mjOAy)V>I3ly3_`m{(-LkiRm?5 z%~Oc$3Buia7hlEgca6MeXg!F~Z#+R*p~eLtej^H|P^AGP+^8}92T%=52ME5RtDpu0 z002q_lOYxylQUN`e_Ur({!TKp_wMX8`1 zNdw_#_U`Uv=hZtid9*Z8Ajn&VQl#<}H3bpdn#^vxNPBH-SRaTADk6wgK?Cb| z?w#44eKa8EasU6E|NqZ_-sk-D#UDNYSpc`o&k7ztb!y+{e@B~-Scx$^Gt?YyP7F7< zHz%^`Try=9lG#j0Iy+<&@7O8Z%G+EVwelT_Q9Ch~FQ)U&(P1l1s#R%M-$t`Wx? zO4(h<9V?f!f1R#-v&S>3tTkl7Culfo9kaSpR%WDY&yk~cqF|s#uzG=Gy))-bK}{+< zGGaTtA-2HYn7g<|U=Z%J(&VHmHgi*d!AWLDxE$c}eoqXtl5?^nj-AiPlKFz2QQ~(m zM7+Ys+I#I`tC%WO;JtH>lYT?~Bs{GS#))%5l?@j9oaMb;bsg zX**ji2&9+t-IdHF3tI&@wOm8M-gWyaqqlb4#0s8WZz4QPt^F!VDmE6r*GSJSm$%5@zg)B|6eAe0CGM)rF(N%{ItQUk| zR#66So2?Vq0Sv|sn&uNVa0j)@*yyuQ6kJIU2C*4;)?pK(0$;{OFRd_C<-BC)F5IpA zw$9QBmA3XiRfB<7(Y7?hF8gE<-MV)hwo}kTf7at^F5R-L25}#D1Yn?tdwG1nl`7gn z^m+vDCzCn#oXsusS(=Yoknb3Ft0nvNlC?nuP*)2-9ta|c>vYy1#1d~d7(^qQbap_n z<^K^N2I7JnujSvKi#-&;K^zLA9u0cyYk~-2sm@-@;2A9xa-EFa6DJ4rwqxQ5bupsO zfA)$6bg`i1L$FoyVaBEs%U4qy6?9%p!o9k6Td^=oCr>6k=Q*m*8k-k2WnoeQj3Lb} z?goZ_*PP>7rlq`HDC>?1u1ss*R+r$za01AI!EEHMVSCU?x+yQt=B zo%El~6s!~Xok-X@Eu02eURTZ#*jJV}iB)w!=yvaqL3T$xyzX0|R>r<#X8# zg-oy|h(=6&JcuHW1sIgSBJdZoe}nsCRd;y|$9UHnJgo}<1Z#YSi|*p^u<#bmDds|`o^4- z3ly#SC;w4T{*!)s0{E)(A6g)%82C2R$FvptvwR~|Oj)J8@6d`ge?^t1sm-c{QMJI! z{|(<$`~EuveZ=(-R`o*6&Wvac_zyMU=kcF{MGtiw_&yzm$Ea0*%R}8-IQ|>|6TlT* zoz<9;VOu-=A2D$yijJl&4>h+h@~~Ti?06-BDOtn=$$T$aaGYYUU=Ibwr#Wm&{C?=4 z27tz|mDUspD-6We-EHkTYYJ-lMW2m*GlJ{mg;5wdP{?_8E>9JCo{*g zV|G`}N*@`rcH0GO*h;W}IcW&H^1Ad4Lhz;P8_MT+Vl+Fn)5@>|%dd@Pvtz~FwF~^L zg99gX_D{Fye_eU)v+L%sZnsjYe!2*q^LE)7kPUK2eT{6Qp_y1x6tc6rJ9In4DtNe< zar0u=j`D*X0M)pfwzf4ZHeT&tj!qPy*&yYbo6V^>_cAJ3=!GOZr8giwa=+&C%Q}lyy1Ip_7}7`gD+}nh`?8lBE+h6@`8;3cL#FK0 zO0fN!Sy%=buQJH!Ib!9L2_@E>8P1w=!0UD^h@iyXZdVS{8{Ef+DTi2b7?4!goZ?hT z{|AHee;PR)z((PFCv;%jzP{eRp2%QcQ-a%!nR3MKxoD!G4Dpdh*%`^fZkv6d6Diw{ zPfLHda%T$P2f2 zUfm~BoMy0}*>8-jTf8yrBp-1v+{yHn zjs3}VE@k(o(?$2!2Je9_4+q4-cKz^KT&E{HkFlI*Y2ISF~l@m_cg7I`X&&WL~}gqAIB{v zw4KK*1<{&t&3Q1>d;r}#yGL*l+v4%4e{mj+{t|XZ&GXnLxQtqf8fQ=+He6U&jIcj! zhK&;T95^%eeAwT*x;4&k*w@<8+SWRbz2~s+90tx||2aH3iG%UBalHB*4xfY7lqg~3 zGOi2zo06PeLj5Ghcz7I{2^5|s*Nfzx{2oNj6mEb~W3YG{*y#RiHn0i!A-W7~e7ZEL?F?4w3%#_{fFc1_|v@unxJg!f-? ziPT{Oeva2Qx?>Z~q~mgg-EkFee{{zPZg$68aGN`dtArqAiXd4wh-<_z&{{5wi!XT& zB9FJVm++Aie(6BdFZW5*CsF?dezk;8#-lZp_!P}KiBHGd$MNhq&X(|eJifcNoqywc z?z1I)uIYCUm+*UMVU_R)?)S@|!wVlkPy0o@P{NAVtm!% zj&b~T314se`x3qxt|{T4OZe6}{^dd}Y(#x$@a6LO{`PnYFGc;0E%=N{?fuu?wcWLw z%&@<$gdfK52rT*t4o=A8lGHqf9m~x%%L1nlbz7UvHP)f-rDCLOpZE~!mYb_jKk*cn zwyq({?mmmdt4}XCOA-tle{GAG1xnJylbg)$GgF^b21Bw`ISJE4ThC%&NS2o*T$0r# zx#8Iug@{$87?&GE5~&Cfl4ed@T?KqSBx?y!rnYgp!|Q2_~=zwM}?omgbVAa@CEkk3hSuw751PC>!|Q|@I4pSQQ?#;e-{k=Kz!49A8?fgv|)s>NDJ57klkjuM=(xg=Drk@%&(X(~e9|X#2`)T+zTgi$xdfbEY328m> zyxaxE``SXXbwais2+4LGn217hU&n;(ibv^*jg!(7?+g26e_VE-!Er{{DdI!&fVaaR z=Dc6$eV1@o$0cl5{}1~QGX&`84bhV9@9-SHPbo!x9U*y;_gthRxoLOU*LMbywvs#) z?-?ob?~Ndo|(R7!RcFn+=jP%({DZF*49PTmiv`=do@cobKWLh^2+}O zP)i301rT6e=Hio0W?z5QKomX00_}dFxT2u=MO9c5x-}7!4H6TS1s;}Qc3BgjHbXnx zEj#Tr(-uRFB>p60f<_a6fIrH3w`h#wgD*4p>zsS;o%#0t^H%_?SY&v2dfINhu@1RA z6p?4GTW;T4v0N3#f#hkRB0E%`ptu%N@I+8@z!TdY2zQudVPb!+_qj~OiWU2I$YVRm zIUWh#U*%M*8^7@VOiBtI3!M-v1se6W`r|e0tqI0Z>ZnY+Vmpw6VM%G<@iq6Pa9(R3 z$3ieSCyYvML}sX8xZn5q4<`CU}p8zC1eFi|XG0{0olpVOPt z?k8Z-KVrmAx!f{QLYeM|`$@I>%7> z0Z>Z^2trC0FvkG^0GR@lAr>5yKMxO+&r=AK;JPQ1*=Q4g1zQNcdC`*;6!bjZOww&P z*=0AWf>`jiJoo@UlsIW|4#WK4%>Oe#zhB<~FomIj&)x1Zf0s+t8)^zUm%5Z=sa@@j z#n!kct6f3N16jgIyj)?-^osN*c6F5V5^bch^i@`)&&)pKny{QA--i6(Uv}0q*iwj` z${?T2CO0!<`7r))%|-Z91A#K z;}(_0rc#ULnsl4OseqK;NOvs5y>uEfH<@x_UNt%+wdFK5y8dafYgNFI5;e zzC4THos2|yVUHS5FjZby-f(uqS!Y*V?En$v4lNlEs%yd#l~Ae0dm4M?u{#b zeQLaMt?}A_X}+~7;g|#)q4Y9kkJ1=XVm*x;x-L_Lx&%AH7Ug}yDb?HkWBVO?JRIv; zQL~jWV{CPGL`fth$b_;URo@ubbSA?5HESk~is~AZMnVlH<6*tOaXiclC!CljqXg3l z3#NvZz#5;%2d!qEm=Y6Cop8k1E)#d5OvX&iBFve83`)W&gc2s}*Mf%4STR|mF;#Ee zvdPbc=D;muHs%tXxjPb0B^2q}mQAe_&{`R70T#-b4^KW?tAq+dF`wDNt`KE0W@S-x zwe3VDPLr`1r?XYM*|-i==UL5!lTb^rtCuI)l?dh4{_$pAQM1j7dU$2jp@D5>auU`W z16Q|li|&CkrMZG$F-;@$kEfq`OH&) zpvvUZx1!Y)BUAvko++;k!+ z?7tNu8Jh)r^KzZKqd%rA`*JkY!wDky(9OMZZLiWLtZVp3SWvmljM7cQ+*r&oAKob$@IRy)ke{z1z(^wZD!iNPnADNQ-4H=7nl&zq|dy-KWesg~xht$lR zV~u>nBtMQ%6ysy~Br|`x1E1nte|a*j>JEIGSDGF83>!DmpU~B)SD4s=yEum!WRiL~ z(&!H-xTt=Pu%biN6CTBL(bhJ9j|uO|xJ19FT7;OoPl@(L)OwG%IodC_Rz~~xD3PRE z!y$1upAu3N!FV{MBUd3;xEJ>cUcZnn5e5fM@wn2@>HSM0Kof!=!fAOL&X3Shwwd6U z@f8_^xPPKP4HpRIXjQ_4tiUk}>y$(xCDSdq0BY0Fe z%7F=lcw53j7Qj$QLWF8Ax2v^CM9n7G6w)#dVTjPi*tzo-X&etMK zN%$t`zOZ=HwYZQfS3#|RnRQmrxA1HUj^cj^^(U0d{L`T;I@5nXdu|>@3E$@I$1QEU zx=%NX5(oTu@L~yGz<0T6i5biJ%}vJNoOlV}6L2rHzebh*E|pJ;>l-p2Ua(X%@mKHz z8OQKLE*4&|13%_saY8|wx|!WfPLl8w5dbHv^PkFi4L@TUz25DAm#(~|&VgU>OH|Rh zZ%a7wE5S`2e$9m;k?cxj+`GKGwP3FPEq*7Uf6sYWi{(kX?Ia7p2}Lyt=2(u8{R93e zRQ4yrlJ|};;m@4WGVBT~H^o`PGpbL5mwYb%ioePD3*KaE)fXgcGWuNEQ0u@ySf$}u zNZq%gn|+3r*XqQ7zwnmO)!V|CTPIWJe+0-oJpX91rc5d)tSZ<%yhm=2V}!Zo91o|# ztzcI0N*2yum0TM{F=uyb4ktwXg`8wF${ZDOs?K0|FA)e*cJwg#Y06@nJuDT=B#ZJ{ z64baO3C9xa)qW>AMX!E{rt$e+2hCuWah>MmloirRGx4H-;Ll~q&cbl%&{ZeRGL%f^ zoGT-0tVi!PVzSjqvuO_NirjpX7Hiis71~Mjgq+8ShnP}>PF5)`F&1fosP4yTp-8CA z<9R2e*a?9&R-LJW6DlnxoPKgR5}n4eC;3{OMtm z7L9z|h|vl{b%7aS<0wf%VjXKO!VMX%H0SURqrVt~AuJqsW^QpXYA;iY=;w%khvCytFa?a3fhDwF5c20wwuTH6 zwTu4BxLPoJB`0mLAxl!%dB z#)b}m;+}J!$*PA-s3)3?=wS|IkJ;ulIH*UaZZW$o%s_=SHQ^D1TCcK4^(e7^6Oksrms4Drh}B;@p1OmQ>_SX`R*mg((q0pgXBT^1jcR*X!B?2hkR45O zd^o@78{6Rnucm7Roon-QfiSmj^hUH_rt5{Hx(jH?ul4kZ*m=LGJljlP|A0(4(oKZ- zbvA8kZ*5=eY3+$|e;4uulL?)tUsJ0d;qM;d@198J=7{IwSa-N5DPY5~32;7-gKpt} zewZa|>Pl!49^{Ry3cA&p8tFrve){%=>f~ zeYTj3m2k)D$%_h>^#fw)#AH1hoh<{vNmy@`vQHjnC_!5 z898rKbFXMM<@&Nr_s~~Lv5_!4qC~qwN@f22PbC+I+X@mIr|}hqZiyy8ztC1|RuwA> z8D=zfZ*|gx^pK1q`sxfjJX_2*+}x zIfKU-y;{gDCy7ckTNJ2IlOc*J`v10R9yv8`&BWc+N+i+|7X2E1jSk9mfDW-rQiS3E zUnYBx_k$Z~$OX`0p3ySaxkuPL2fqgM9!VcW%5(n_{(g1o{kBU-xldR+~uI}aIl4W zG>EH4usP|wX7c`DPMie}S*2+@kB&;8a06q`;>2^NMBkI?Ws#|iBg~qIH(S>Z=$Fubc{Xm@h!|dg6=97hSwdH4p3G4h=T=#i0pD_GRdQE)hSWG|V24~!5 zSQg{wTvk@{eph&M8tght&nAV{#TYsuuZG|UZz*+^}Hr= zb1xf^E5{$XTL>oO;u_O`TpEAnV6HM7Z_uA*`V;YBSDp~xkzzVew0T0zt)83<`Ww9| z(Em=Vq7+x z8IW+{3F6r#kV`VIc8e>oOb%t*@6vG@B{Y&Zkmf^47UCRYrq^+QIV6)XPLM;geXzx9 zvB?&Tg~#EdU_?u(PK(6TB)w{3xms3h$wA9$BQ%(~V3X9v7 zuB6dsiS*atu*lrAiSKx9eh!=9ZXN?Ri;j<5EHOp4C!<|zJhM_d7G;K{2_Ef>AVK`I zq8JYTPZlS?y~59bR{k4x6{RpEh4K{UrLZXAPoc_HlS1PFYU_q@_F?dJ<{yNsa~Ms5 zwz?FW(^yyU7n}aW*hF}A7@Gsb*c#YTx6^fT8i5op>2&Q(p{p|mHI42g>jgw@8oQ6c z!beU=5WSd(N>t+lSS-`TcV^f|_?6YSQo>@8gbPL((0p%y0!AP+uGr#74EsrjRUmF~7q$SX-CnKF0qqcO_iO6#CP+Durv!AOA4+2X^dePvZvL zA>35-IO+lctLv5yo9ot&6mE0X9m4I|)jN1~K&*CVSMKDM&x)0R>+=lgy5|tSID`j= z@le2L8^*(b0q;S4Err8rd_9dL!+0v-EAqN+X*_cn&k=lfxBW0Ua}Ln+?jrI0eZrGW z+9##(qXD|#ExBGbj52c=uQ9Gb{rTX?F<$>=3cneEo6#gTX&AnkR3OJ!s=usj0GHU{gK>|<~n4v_sb zd@w^h3~2ixN`^@eq^abHm+=_X=U}tDr}&DBmO08DZYf1`?>&CNT~zL{?GnP4 zI}B-meGY@JBcHCp4kI&++u>shgCkF{t!~O=R}ddOzH@TUG7u{TN{Z%-=QG_l!Iozj zhXUod@Y+H$QA2K!=6FsXI_cy=e*`F&}q}#{<;Y$!89cZk%5(xb?9xjN_Jk>@(gn+A~D`lkCoa zFjnkLg_p9srm%*bKDIbZ&7vA|UUd|bZ4frA*z^^<9q!_+9*h-^x*~V6xiCc62@~Bg zOg9GFg*NWsV9jcSAGW9I<^jz28djIs>K_zVrw^NkPtix~Q}l@eEFGrX8L^h*IZ!`L zcd-9|I!$*Tq|dJ(rh5Wy-r9pSn5O%G>)rOc$LKNO5s?pVk3$Nqx7K%*(bsE-=t+?% zIguIZkZ!}NBe)lmnf{EQ{SqFMa7@Arz<bp>E;Qsu7fl)IP$g&QTDS!320E{~f{F z0ziMs0*!F4ES`)8iT!5ClkJ;70%-OmKq4C(0E?#LbOa@^k8Z=<6wC8+mL(j2GB%jz zyJ!^Ly@mNgCA4`28-+e(Q7$GR&}Lu}1D5d8yQncYE~F7IM>&e78wIOI$vH=q7US8d zGzU=6HHJGt{=JyD8eqc`F0ZR#$2x}F#wB$(Yq5_HkFy|2II$1YELUQ>BDo zt(a+f4KB+YD6_naS=Koyx6a3ZDb_`pZEe6D>k7E7>oC{43-heqIMsR;=3B4B0_(F_ zXnhkN+bLLNTYw5%9TwXfQE58|r`gWO>9&heWz$h@+lLz4wWzgSk2>3J%&#oQXtNrU zgL$;G97l)g=|JsHcGYJB>qVAI)3>~}X?l)5HbpP27eN+it1Y7!ImQfs53gZIe`x>} zjPi1zEluC&_a6n?j-s^w3ESO}>#a-L26h24U@sq{ z-=yewY5Kzu{k1kl|0tt>rRYDrTf#x$TFFuHPHoD9OjOi$5Wm?wQ5y+P^B(`h<3j|WH#exHHsH#>GZ}Ar2`+5A{?f|fYiGZK$b(5WCfqG9}DRZeS8B1+i z+b|v)(s3FbQ}!u2!|fl1ZH$T1!rSuFa`qgJlFG0ka(*Q89M4 z`YLv$4-t&V0^T5krvwax4`BEQP)i30e$GQa%m4rY>;RJ?795jqW*3thel34>Y8|z$ zmyNqo@Yd-FRwycN1W`}~1)%& zGmMP07jR`n!%0Io;;AbO$F_gqL5mZs+duQcP$_DRgf?WQM!UJ&+}U;R%U}$Zt7NEs zaV(W!SW9&1g_`%2@NP9vQ=z@n*koL()$jc%zu&?*L$%LG+*3Rby^C&N_?d-C@_mh; zBoX;$&k9B+UhdzgM!=;SYH==%;UN+AvtP?qrez!wHF+RonH@5$tp8aR{D(KL8A|IL z*EVd-R$yVyMj2C6m_W@&1=D#p&oF*OkAWH$7Ja}NWkgX{%Ng1kg^d|n7pYoCi2|70 z>~vmG-Fim7@r;Ehpg>E7qVx$+O9u#QAk?&2lc0Z3e_9D(TxGRB=gxBPOr~wxbXukh zOgEZ6P-t4F6iD~bB*ms74y}}%;TA7#F}6%Os`HB4|PJ zf%;HH1yOK8Kv578O7p(+-K0DiJGZMJXX~m@31hQu%eckv@qFaCac=JtoE(R zba!%gsMCxlt;*RwTdKOvo~nqVahhdzo@rujVsUPNXF3|iz&0z91XT5q zNvpdpDwJmz+HgVs8f=_{w&_~5I$xAwwFfI8%Fs_r| zOH-)CN8@RNhg@`$j|}q2w`o4|QjvU{;Ugc7lW!+8O@W<6I(t_{lBqR`F*><^@FU0A~r=`_`9v4Cm9s5za^WGWdZU6)9h>P($#y|hRae^(Sq zu81VSSv=9}qqFP_g>XT$13us{Z5ZuMOXT8b(^A0ayuU_qj^PC zN6VR}juz0ebR^m#%3q0NRx5o3JMt77oNv(TQ5@uSs7$ZkORMO7=tOiF1G80ymL4~h zJr{Cophh9l#8f{&*b%pq!B{*Me{7G(Qf4F;G-JKs$CgaQN>&F~?&v|s>IkOd!Olpm zBWUd~+f&ir;ORr_daDh(03ecz+h;LNE(De^Z!G0)CpcU=iSX)iRS%Y zYNarfGa0$eQpQ^Eqm8slbnyYERr7PVOyV-}VE22y>t@j2Vx>e&^<~Ffe~OPxYLheD zu`U{EGsqI_0%K(bZoLd14E38mjbN-fWhQ_kb5GZ)%S#cl)UuJ6kD1*9B`E=<0xq#t zPKq*}k*8WY$4tnbhLjvEV0pM$Y#3v*xVStU(wG(&Ftc}83%sIvOKr;h>#V%GNhSWh|y<}4FZ zT2)%;q>T+@kHP((CB8+mCAxOB5c6;eo z`ii6~R%}bE%SU@?f0LKW=ys+VrOQu@WOoP)UzY&&!89^1AALg*x{SUlOd~f-;U3?% z!TnCe2^d#hTQVL^r!3KnkM0&gnnT}V&3&QReWYEbcfojPArA?5n$TXyta-6{u`p7z zf@`|X-e8xx%?h?zRxFq@yW!+OllIRYmf4a;RKCIyU{LRf>COoA% z-910plZazusy7IC?Ul1^*r>|FMs;=`uoV=O3PzIf?u1|zAiP7i1kD6k%la|orjE;Q z4|XQv-GG5qBApbxOR7Y(S}vBKT?AVa(NJ(+5~Eoj!WXY`AaK3bm{lfe}IJZaY#Ix(>*;2z?lVaJ}Lj` zAqQ1~?mjx`rJZy?QY72Pk;zDkG!l)=E`q;CRifn|%AQ8D_#k~xtp6c^L4kRlzVD+$ zbl8jJ^9W!e9lI>j!*oi)U_5l{g(K2G?5MdY(qku*KPteairYW-(qr^rfGI1Ml0eK9 z7?B#Te~hKOt%Nc=aQy`RMArXw#6fvWboy_&I_j~;c*0s4wYotS$nbN?$)2QN0GMLd zj#PGHbgD8G!hcCm%kp0#dK`D1m0+`1r{92MAW9P=vX7n>BzcB@i+pU%nm{mTL&B75 z&$QDUfy&<@<4&5L3Xy~s)2aVaMh7OJrx(2Re|!3aoQ&kv-MtlQ3hw%68}eQRg671% zEZx~DK(sEM%8Mc|K~e}|`GZWW-+K(pCj|app}$HH`Rzdlebk;7*MjCeE47bouol)ug^05hW$jaJE)wHayU*cm2J3Xwii>bCLJ~H04 ztZxV=fx-x0z+ps-9K^ThpJK3{3)D)Mww)(+_TaPxq9@YZrg*F=9YylExIp=HVvEeV z4HvP`%U&Lrt0J>k(0Kyt188@7)J(#^e@jL z>kB3?9OQYj5{2;e0;l9+rp~B|b#d{QM1<+&(vjLN8?EeeuJCdhS0X5+;&si-f9va; zvz%4i!l*%A(YRuv!KcHPTQ;n!T5RwcwtScMrUXBy6cP(kH(toK!ttVPx+obTpM_+O zLpg^*;OnYc7TJOKH8mxR}rJ@=`umO1a(gt&XWU-yD}Agrl-AB&_AULTngy zZ}IB&bt@WHZf}RUJGenuzub7 zE0=FDxDn(Ky~X^73wmB>ue@LsceY8bw;5>$89<6~?Bf=D>_U6YUiW@`EL==a!(yXm zcUy-!cNiY#p2pOE!eBU3vF{a1e7uQ2fFR5lPjE3x&*IWi3yRrfnmsJ>e@JXwe5+N{ zpcrnnQf8;A#G*3_(xUF+0j3}4+evmGc67x%)*y>Sl{2>?9^aboDd7HNZQRh?W4*UY z`^XdTEjxa8xfzW%1J5BSi#xsC!CNM{8D*cd-4rytu^@VMf$WT;yZWrxXMRqa+TD`O2&Fe<$S8B@VFsB-MNQ z8on05xE_^-lq?2c2W9}1*+&B(UoUCfPW}vrk@UA)tE^NzOlMX>ZR9LLN@*rC7}c`A z&5Wik2}M&zR=8RGgjzn&NG@*Wo0t{_OA{8d7pcbPbp)jpNLJcah#3pYBes+@^0R{! zI8x_eRd=$?;4dN6e<|K%Yd)kId^6&N3YTIb!mW?L%qH?bzEzSyWTdX@9y5_L7)7>k zMP5N@@E!#FJXtDp8_HR;#+_dfq8@~;BY{ncsJ{k`&W1HC>WP{_l-Y%&+sIJxb?)=> z9sG^qYGTOAjw=tm{4I%w--a3!>h)_w+{brGSu%(3MtHAFf2HJ28Ir1juJ!IG-uTMfPs4i!n-qP<_G z*8G5vf;3C)_^?=%5}!mZAAb*_hg$iek&olOD6_kD{ys=r2{@&H=%N=uCPV2fAK^zl z`~!Xzl9j8Ze-qY_ss0Gz2!tQY^P9ZAI!gi7BLmTxkDn0Zf1H1UlL|gC`1ogbbVIGA zi%qJsi;+3~oPQzXPpP~Rwz>?~xURFaG3n!{?Wte+_(uM$+#MB=0ptbl#S?kYY|4!4 zv*Wnbv;5m4s^jO77#u&Z^Y6g|@TLh>nU7yUna0oae;=Tgm>T#K3NZ})8P{GR)voOT z*+>r){)>-#=!3$|%Rc_FjV*u872PB1hGB?#bySU2ppMVWX#XJ@?Q3ANI;q5G@IRH% zlJV#^YuMro(D<|_RGMK9TAi!?}*9z1$x#@R+N<$S`dzYC=f_QTZ zG1E+Re=N8A$ma*`lyLK6h@j!P_1Sexd>U(-M!%6AI1*+B;|95ghP3wk_RE>3 z6YY253$jmQKCJ|GFaJQBobxgJcNhsTmad^xf6!W*hmz2|Ib8cBE#T3nYSYy7WJ7#A zVzD!NGuDyhIVT130m#KO(iSH{Z^!*ekhjW$&AHg5%8w+Q>|P*UTPKcWZTsp zfA27~D!|L4g$oU>M!d1Wn~trT)4f`mwm|Ster{0jLk-6rj=P?zEtHkDBc6D()4H}; zL|{fztKtct7NSjF?JNy-@6^&UOLJ|htT|`IZ*!~EQ=5bn?L4nmC-2Eld08~Hfsy!$dlQf0Aek z)oMfA1T8F&cfc{m0b<&>Hkv&fgngz7;>u0w?lvot9Vs6E1xw}WNt#G5(h)$N_-2p? z-zLiM*{b!?IMt4)31~fp{phiFF?yBc#vY_9;Zzk^m)vWEKbJ05^y!H`t_YJ;UevlT08~bVT zp>rIyPQP>J9-3M1cP@=JI~JXfM`Y42kVNe(@y*7CR15hei+591PA0e}@~(Cw2DI z7BIexN-GsFvnmf#M3}u4{qAt%5t>kW$oUoWR5}*)k&_=e{-F5r2g$c`mT!{GXq)kA zl5Y^I(eSs7Xb>{fbefax6iH{H>KvnSIxS)j3_`FDS&go&VOdkB)>KpuQr+>E=3zY7_fp>%2i^!cd^053f2akmBtQw!jyn+2MRz5<` zeHD|E1Jv7;p$|JAppOjD$3sp>t!rX2-EV~4ewVhJf&pj1ouTW)wXWL+U#$wb9e(KW zvwedvK>Irb&Ld<5oEf^QDnmDin?z(GXFuI?sMh7Eb^AeM4^>zBf8A$Hq`@l&=&Rw7 zo}sTn&P4%d@o5?AYXyB>1bej`M)A{1A=VNGN8j2d{Dm`g7i7M-L4SaBm@N1!Z+2ER zyDFRARn3#`2{;ER1BDEPp^pQHg`Z-@PahfOn=|x4`C$lVI_$U(moB9m)h@)Rw7;U? z!AZx+uhS2hr@u)qb-G)bAJAE<&8%^~o<*ha9;C;_>-y>O4E;>}{3-GC zPvgt48E*NESjrq&N(Id3xdHm4a?U^PvUT^D*1o|fU|nsMRR`(iaFdK>?eo=sdM!i$ z3OOe_#Y9~&e;$`IPWLS|p(@~V_+hI@`v(6~6;@V|p?C17Z}6jQtE3&W3Hbc6ee#iK zCdKfSakNZbcd}}y!fd3SP4iS+O0}vzi_TH)DtMo?jkHO%n`kqARzX0gYP%?|+B99K zTKSZ9pMxxRq1{DaQT;pUP8t^WZUGQTT&E|MJv=7Le?J5ICHbCbdD&^5p1~JcG>hDM zqc6j5l;yrfCk-MLI28emXKCni#Lgk2PC=gRA)w_Po>d?=%J#glxejc&4lP_8)~zhS zu^KxNjrj43@{0ZJE@5MU$3Mu$jr-{ocr{OM%^!sYWOypVLkR~mJQHgCG6D&W54ikp z=Or1Qe+>;|Zfv4Rot&ZKHjOiUw(^z@AHIP3K~rPmxb5 ze`7H~?@^k}gRqPO3$kz*BV)vznlR`~hn%o*&<5}1%rAcwQ|3YlJ| zk|?qPUTp}fI5}bfhOP5<Z*?Q+aqlO}DM2gs)P{+pF~VaeP+hI&*DhX82Rt)m2#iX<5xT3{4?mfHG1$z7nTx zwt;<>j^0Fhg0MNzDsdBtiC53OMI6-SILGf)-;9a;daZM2IZg<{MGL z`J?i$oMlSzKYuaJu@~zFNW4vJB!#teBQT26Lw-)NEytJ!KR`L+_++Ju_^w@@1ymH> z`^Q&Wx^wA}?(XjHMnsTi5fGJyp@|coDuUq{_K!2ByZAzmd!98k_fF z9fL`o@dETaap3Y$ODA~rg`bdaM^s$M;M+9X{jLco`a_#p(qt&>=A*i{0{pdSFGahm z%-v4?nv9u^+>Zf<-KvS%8z<~XFnc_y?#OA2^T72dqB&*JKQ$A#>{uNJ=FE)O{0RF< z@%s5NQtURvsygx5Wc#(8r+=v^;v_!ZjtUXK*I9hxwGb~!T-qk7m>1XS#DD)4dG`at z<7C`)byKQ+Fq0~;Kcs?oy5XVTP` z7i{8ran2xai~!Fi6$-OW3q}UrQ4em)DtO$>u;845&cU;YJzZ01JX2Yvz>WNErRr}U zc>AJdfdhPD+bvmV^sNo!76uNYqylyyh;ny|@0^UD_<1T?2-Y z{4J7O9G~O|jd}T&7-pVS;Ln^oi$rgnlT zzn&6ehHpc6%27kA?7^*h#EhMLqi3f|aOne~9V=ibiW>_N`hv-9XZ0vxN>K|i-HAIY z^K>cb_~c$3p(h&`+1L_E4Ew_BlxWk-%4=HA9$MsS^Jdz2yrbgRgzj%&pWH1yzKaXn z&Mg4_i#c;qCRA}m;$>9UQ8xkThFBgKrCt)u#Qj<7G;vw{rwsFqT$zx-FXHDeZATVy z9of1bJekMD6&5_Y+ji#Ac#bINv_4EDYADsEF0adU5@?yn*MawaH$k9n|KXBxITP3o z&o-nl??q@7BwnY~u;+$L`J*t$5#Xs|muK84z^u-~SEt$|Hc-O>qH@ebnT%Qr=R{7E z(l_71K5mob%HD~ca=mps$UC_!U|!OBs3O*_Dq z;0l)Z2vmjv1mcrKt4&?m@gcG$faQj|x)=8;__-@%ee&naZqs|}6F$4C)Bc`59-8G_ zGW(>xh9(|u_9b;r9Z;Tkzt2bd zrtBW2_b%0NgO<+z8hwd%Cv;efeTZ#Y`SeC}im_lNjbGIpKh1ZvD-u$NK?hxRSje_* zhRkIYjI%CX@kD;v%VJtMy6Sd}^PO~N$jC}!zCz_5zJj@Mw{U2|!mVzP{T5Ejcu~SV ztzta7&&0@nhe;7+2%*}SY+z0jd0VnETNz{3pIe)gw9lFlsXZC{jh;~K%hoeLfg^*y z*V?=0MDZ2;rxh-JG*XP*aAqx6h zYtS|05Jy6>^~?05-91|p^kt8Aex>h(Gg@0tRTh1HbfVu)SX#Cjqm}GH6K1E9`M5ls zRnyN_GP@EfJVK#8(Wnf(rOmtX9wpRqn+-(=XJ*M2FBYCpu-WZJ9OerDBtCfF)O0_3 zNHi(`bItiP|2t`rq9L>Lpp3w$bm&(ga@H5&(h&U%ReX8_t(cVBz@~+urYKhWF7rNC z9!6^F=SdfRtGFh&n4)~1+yCYj)v~_uqY8}Z*AOJRyvpu*p|bKr53OdV0$*llggXiU zlicHw#{@X(VW?2{j3HbzZGNnmKE0D$J15z%%pb{J@HCH`915OpZIRsO7xPr-I7)t; zl=oConVGkx@`#0IcP?Ztn0Wa7JS-IR^=-4IQ1OKb3|B-S04+Ue7cm#bM4MZws(~RlQ`g>*ETFOQHrZdlw-tUd+FVa5L6t!`f$_#c z=0#3QdqeQ-_msu4+bVg&#|pNh)3Pho-3HxHX0oDltA!*VM>@e^t&&0*1SQTw-*azz z?~U3|ytOM8OqvmxLRoj;C#Iu3v{sjldsM!boMq^Ru}Kgn8rydFGz*=O9$T^!y=(>% zU>ysMY7{^;g{QV_u2S%wxlj(dlmnofnYwJISIUV)ZWNS;=uE1*e=>?t`APtT1?45N zF_)pLUh@mnp58oKRn;o zt^#LES$mf_K$K8#D2_XMSCNgEsMy(TBWk4aWDod#$QOPSirnA7yeKO5bHR4Br}^aR zEo;f&lTuUQ5JU*qLpGRNga8&v^Hjx4IV{!P?dCOXvD-OL$9E<e%`{JaKESsX~Bb6ztt z{@bbOEr)k+=p9X_hyg}nyikii(owO%my%Ad(z6iHSQ4m{ntm#so3x3zkCFO5j8{II zY;b-fC^3XeHWt>DXfkE)$H(AshHE_`sxklm^bqC5spQ0r$GA zy-C=6sP>F{f^#a#*{;pN38wvI{<5sv=MdJ015)3*{`+GNNP~&yTg`m!RBD#m$_Irq zsqfd4J{+(r-g!8HB3K9`xHuTDQMfBo)kYKJWoGS~`jP|wY)Mklvdc7X(3dtszqz%- zIYWMEYc~G4$g!!ceIa?zBR?r zbSTo^VjI@Pm=okMo8W61O=YpF4*B>WbH~){Gw5j3;Dx`D93s(e+duN31Tx1Z2FcYPUkE2%T307335)(gd13TGBx&qk@cyA7>=5NL0KJ3zf!?ud zdBh=p%@5cKeiGNEo#Vg60qksO~38He1p@7o`qoCN{Po{WsQ>370@@qPMG zxi2gth9FeU_qodwZ|Xf6lw#kXp<9PGD4QHlswdj{#}vMG^pUwZ+^5(9@bQ~4rVOiG zy8T(CYZ(fZ3VBn!&Oj!4q&3k5-6X(K7gMXX9~20Dkv7-B?`gkcbciW(5T(?$xO#8Z zV~Fib`Waf4XI*}MZsGFs3`G-8Zv`z(VR{0orjj*~5P<@cYF0 zCjLZGHC8Y-=h>XVW@tVMU=M7RW#Kg1o0x00Pb59pb=x>lhqy$URg~u(GjzBn3sX;U zT9KE1)BWk8agmATqAkJbw6&7zaT6BF9%5^BSjkyOF`&iHT2Df@E8XDy14>t!ru>RE zV7SlzZPWbZR<=ui$jxC9ZimTZ#Fv98Sy-SzdF_*udit}mQZLC)z~JOg|J0?N1kb&b z(dqVYj=8K#d=h8S_QUc`5<2qS5tFZ!)vqNDD2%`|5AP8_Sq&ld&UJn?Ebw+np+?T- zV+ysalIdGY4*c{?%pV?Ej>W#TxE#an!akF;cVa5aJFFnsLp&Ui)CTDM!)Ci#IZufb zdM&>#+z=gmtEBFtM}Yl%1K5+dRkY>1T>f?u_K$n7zcl7>O# zdRN?op`^%Htd`+yra56}+tEqtCNp+R!n@nh_#npl&$p|CyoCo@m~F**ceIj|xOVyw z7a5Ws6Jh!@xjOJ4oF5d{7ZCooGzMwV-Lo8YI%~iJs$)+k7y4`HImjD{3t$*!D=Ji@ zK5WF~Fp0%xxCe`8C-fG2yfGF!sJ|Pe{Wz<+Fg}EHOY8VPn}R2zZ!lF=W+r%vL;9DIJHM^-4S#6O7JA9c#74PZEM0(#A^-9_GIy;(et>{ z&%Up}7RgL3-pF5Xm8G>!cEd?;n~Z9xMidL1$o?nr*sPj2ddeLz&RM7>aDJR+d-nP(Yj1pr%&=IGV--D zQbO*~dXc)@&6~{H!3)68#6EwdH-=a4Wbf$urG6sT8c)ET!rB6}fQ6M*d%dDIzd#LE z%GgLy-VY&ZkTFfJk@g1Gqngx~ieD`cx8_p1X9jP&;U#4B%vFBcw&3N<*CYQd2)UQQ zIqj7=-!(W&suot#HIf4JWzgswsz?>6&~qt4%WMthE!IO6HISRq^5buod?O_4AGUtz zkctkew#v&PPAPwfkx=DZI{jczcd4TD zNXZCU(_ioDg!;bOz>LeW!E#~|s%*9GMJ5w|R{<5A0D-)FfQDw27*byc8)U2|b)WiNzJX%M-m#suetWd5ubeekH zgWOF?I^h=QatWelCS!MLC}rF#jdaG#rj7M;T8`U$dsP&W$&ge~a&O-o&j~qAhc%lw z!;O2;7Q5aa)86$`_xP)$qakkX7sb&I#0sb1k1T@uZiyB@HlG)5m8Sv`y<6sbhSZFq z1^D|uYoB(vzQ>qzRmr@0z0$`2Jm7Tqj?nM##Y?IEUiU{%uqF9NNz7x3 z0}5i_ZDXAL0PM(4me^N|#pvn8xY$SR21k->tqL@`?ohL%c9d!#T4~gl8_|4WdQb8N zJt5>Uo;{PW{V;W~mBp*EvvHsO(JLk5Wuh1D7{j`g%h>#8Z9VFw^6q|sBb@?NtU7^;_(sYy6H zl^3yNxvbaQC*&AF zcoN2~*v6t*9{Ox0#?KM_L6kCp;H}IE;-wQQ$~Jjrz$RXAgr6yW5I#d;o|DmIrSL7l z^pWNnPO6ZgM#t-R{cn7Fsa5t}%8S_Eds)b4b9*2p^}Lg2T`>&eLF|X9lfvwbOwsko z?pQ{23dqC}h@B1;2@`n--3XJJ-}BP*+~bfQc-f;P^sr%ZE77jTfUs$7 ze7+JY#RTbdToAthy^po#Ne_n>53}2JdM&uANlNa5F1^eXhsoLUPQM&m{-p?Zgh^(qrJncE1v%U=*RS9oG zb5f+2oUETZjUO`CsIi@P5}v(GY2Sy3gv)R5(^@ILLyLTHgl6*m0>h86xmJhtC*JCh zqx3&a(-ux=H2J9@XRV(EYwswOzr(eTv-t(QL_UT_3x^q)G8dBNE>WMu-iHn0&h0_? z!k*(@h8vtxuwUF0{Yl`9bgIDy)F>_!-Oi(gUIC)Neyb4X9@g|crVfJIO%*!qJ9Ap@ zThzzidz(g5su>u|l`}>h_)MiEF7dt<(P6|Y6}j%5S@^0$4GEdAi%GS)V4>jmPTEej zc;)kzUKCzToG1gHJ9K>LrQ%w&QrgFb__6hPyWB(LPhHb2$gN1s!M{7X*^O#xYS}aZhW- zu?Zme)BE9FwNw~KbXN<1)k=V+hk2GI(KSS(Yq(xgnDq+seJc)j-gRv6Ktp_J=NE-* z;lHq>As#pn2Q#`E3?!Bv#6jr$R2eiYeT^f4i`1Dj;8DFCr$Mi?K{xe!clO|Ubw=QD zGPEf@x_m5}5xrI(!gtje!Fpcsm6tdgXhOGG=^A7$a0R8;OM(Ad>i&1@iVLG5HaKAe zGxn9~BwVA6kM9ahd8yVni zjbh-x<~ZnSk!wXyRnU+<_^$&32qbb15Y&d7G_k=6ns~wgD-*AH4XQCjLpInP0%*B% zcvTY>2B9h3q>Tzb+av-0qpz%l-mKW@U39(fZL=$g#aQakNcpQh3j&E>i(X*$FLx8Z zWXAf3y%Oai27wyEAQ0;{mcs5|77xzf!i;^T^a3|-p~5imyjro;f&-6pWBe23uNumK z`~1-RUsekIH{ApT;=NW=pU=M#8Qi9o8T>bS0|a8b2G)n8L27te>n-qA+5vhPjiSE- z*PxjQGz5mn`J+o&+Oa+Juwli>9gG}SH!zB+cGqqGx(K-||N0cBSZ SeJK;%s)H1Vu=dXp7` zcki{=+H0?0$am=TH>ieWG$8byNR(Z#_VWe%LcE-=EHhyI6@~hK2FZVN+pf;Ay407J6;#Akc_hr(}H57tV~L zs{_n~stTn6y6AaWRNuT8nf=}>A=kif1kzNKomY>dl`XVp@pT0{n83kZUw*>dLsoXU z-;~uk!vUqq;$j|lNrD&-fD)YnZZ4U1-!kUkoh_WUQ(f`H-QVh=S>VPJ%~_yW90{kH z3>ZT{-*`hGTAQl6&0IY>Ut?Jn${qc^Ugkqt&-~{h6U7}AE(amc&}$Dcxd&VBTQ;|~9zhz93_5+D=1 zGUFN28kG*CR@tN`m({rw9=>GNUzj>pQh81GI05J4W!Da~m=x#9#UhKZo4i$vxYf0; zw6Jawy-vMTinQ%Sr7JIO^FgqPa3j&^q>?}$D41SuMOE-x4G=N^qT0P3LvQe5&A45T zQB%a~D|g2s2DKA{s*lz1P?D46a-i-nln`p7I;Y3sUHK)sX~ew2GnWkpPa7Pf4L^7)5W}^Ic(#q8yzYMuv9D zUaR? zp7HyeboWiMgNQCi@C5e_{k*HU7AgO(a{!)so&>}2mguehm^0%KT3%;-KxoHpPvIo< zWTCi^yj8L&mZZ;2`Df>}fy3@QzW-2tBc`6$t_+UlxIQ4f*EfffGmR3r6X%?<({3&- zPgR#n;vtU9k;h@?PL(7h5c98Pfya%J!WpNU*yL0c+RpKZP$ahT}4Pcf|*}}smANW z=zQsIJrX0O160@H&6d#OR|p>^8g02xr1OD%G0w4)sibv!tDI)q&%(W{cf#((NH~~G z0+WiRr3We3W`H>HZKSM8+&M#4c5G;EzS9_?Ja(r!o;B$0!^O%@4dFvZZ2LNm*sx!Y zEqCFBn1EPGNx>EL$17ogJ-7PeR?^wuaCN3uuA`|pecS2>!oC=I3la>O z{Eoz?QzE&pi6^)>IbWfB^99c3AlwvX31FVoR#-~N+Nx_=UZU$cy~Ai^LCy!|XPjLg zYX1bh12hl8IDjXTa4#uGn5ur?g#+UxI{Q>ktoQw`r5V0yc@5dJgl~XB!z|OBN+=Mv z>=mluKX*L+Wvy&yQH12-0@J79$X7tLm%kz)Gd(K4%mwj2#USrXdX_>l-pqIrDHW4= zTY_7b$DIwi4D>v*kc}K$;K2SNub}EJeQl$+C2mINljjEf@LvA>OVf|R1KEq;D3dtl zJhvoVLgAW9tlbPbyT9b|d~+d4OoL5XQasHf)ylzLS2$?K`ET+yOBV<~C%j*9tpL~C z|8+EU;qTV+|B5Rc#KBGiQlOv#8R60aU6ypPzd3KLRLTdJVLyx_7?ay!^3~7;A+tG5 zZIC+!1FE#-R^mOf!Cq(M-bZD2X%AcvL1N#PYtnELpLp%Wkoen%Y_m0PVWrzV=7MHB z=0qL^4nH1W^6?;8|3D78Y;2&F1JxM~H?Xa>Gqqd1XsT^>iYtjWS6DQi^t8o+-Uj#~ zLLs!Lo9eBd^Srq_L+aLR9lKFAi#3%fzqP#BBE}Qvv>36%TFbYe>)QdL0M+nwH7!o1 z#Dg)~o5^|%cDN49R!8N{MU(+{yPvIwGk>)u_qiqKSoGrI_^PG1upc|l5rjC{R#~#= z+y12Mr_FYUiAGeaZ6B1i*LJV~oqd>TGP)!r#3cI+)^dkw;7ajv%f1{jbyjw*;X9WP z?!sgAc67q);s+5+!$3nn0T$>ji9r;*{6hs+n35YPzFakBF+^_+a|D|;2MTqy*{u@o zR@|u?bQl5dUjj757Mb*=MqXAr*RV3Gnv^1v-AMMw3+5?{bF7P8ciz;9Zu^~M?`NGvZb1^2pIE{y9sg6x)7NGE_h za1V{~QQuxnIqiq>mw>YFUS+aeV~aJcCpeq*Aw3Q;(aTq;>k$&T@Ya7N>ud5$cUG3f z@B6D%QwQB2))+t#vZt=vR=`fFPBG;fncqkk1{`9olZL>n1wcJ9^$5;_F0wma{?otz z-}RD)kY-*{j693g=3~^9wksA3=Zgmu7sb3k{Z?`V(LECg=DeEkNG z%p?Tvi4|ho0H6Mewda*2jhzdeeLNxiFcn&xdzcly{fkM}d-B!>L5cBX55Ne9hFxU_XpjQGReopPdk!pj8Ow>7Z>vNy=QKkoA{zcb~dm0Ry5IejjI zEwuyUF6z*STqKy~Mg#jYW3p0_rmQ2>2#=-7WM|e7w+0rrZng< zv(6DhYqJUkHVA$@85eBab_w>`AbXTskx6=aOo*0ol9RN@~z%;wvZ*czzXSH{Mr%agXfkPG0g$NJrg2bmMuud z{J-$iXUkZ3Ib+&qPf=)7^yzt6# zHd9SOf$>jO?LM=IlHzR(r=xz1iLYC3f?9W$c9#7D&(x(x$(Gax&ajH1@?d2LajSd; z@W~KU`|P1Id1%eN{X00Ju&S~ZH~K3Am)$)Op$Dokv2c|`(a8R*#{q6r4=EqQ#s|4K z!s=AlU++vtJ8e)3Z$~YDSuy_!y{?vpjNqOhR%vF1*NVIUvsonNAi3QGD@9|rNGcAW zg_`9E3n2UNObF>rTXa#zP1xV|ZRq7&;9TeJTNgppQH411FuMAT>!JP%>p^_d_pG5k z?sm=ezkG);9e0E>GT1mcQi0;zF1b`ae_d8_!VTS$T<9$Tf5i9Qeq<%oZp~V4vUZLu05=C* zCw>OYfvZtvUB6YPb-ZslY(27j-tBwI7UObJ)z!v%#O9}UKWe1eqPA;|QQzyNRt<}o zwTr2WZYILR9KbWMFs{)ED@~}72~pl!3C9eK_`)P6_rWPo*NODOkNZNYB6XG16BA5L zAHs1j*b+@5sKq4Qd6>Nd@^JhffyAvZF;<9dFxN#pZJrMdn8vi9^gp*0gZn>6N<1~Y zLv%y=Bi6aG z{;+g>u)N`$00C#9(r4@uL4gT^L*s0upbAXYk)0Hhp5~W3WWyKIHrd#9Pe7qu)0gkk zo&fB|_h!xYWa{dbt?~vgI01YCHQ)-!j*J`f1(Zj|j$JAcyrq`F0;@u)_I?dWp&pO$ z_66;c83H$uz}ckLsBrWdLHhTys-_F_En35;y&Xj-kRr=iub7EkjOC;B@p;xy=`W(e zW6}vZIUhfVzV$|BV5)C(Vnn~BD~m`q>H0pse1UXHQAc!siF^VW$`*Y0A%vFB;pctV z?Ea26{3HqWncUANinVfHku3vX<*-0+rd6bfx&#CRrfcJ7${SS%lb4dHg>T?lh2zOl zJ_hw)GLk+?IQYU|8;dA+R~J9t8pw(pMCDhW8CMS7nuNvgpOLi> z>#^Uq>AgOspbf&U98rwg*1EtetZOI0f5ZTf(5LHDm@7I*Qm&>c_cEg~}N zDI!YP;$ykUPN?~%B0Jy7#QblbB=Z65@_2_eo}xIanjE`NVd3;_SO4lZ;ekeL?7nK) zGNxX2io4qiwptj>a}{wf4VQ81Xam;(l|ncwSZsC(_d4tlBVK_C8`Y17zZ<2t8m3=5 zEjA3jv&yj9I!+ONF2axf%Fdh~LPZH>=GX8WCb(KB>+Kop9?aj5s>Sbb?$HOFxcf?vbxDyX1-}fP?3jNpU`I@vvcWHU=YX zP=~8hui+X$Ig}jsz_P39x5@M-dspnnv)Nx0a|*89MXH07UnM9b?${k)aH)@TD}RW0DT3A{WeFxXZ7aGh^*vfguJL3) z^Gq&-L>zT*qS$f+b=DJvXzDcp)=E(jw0V$o8EDhf_xbh&Yl;*L$VWq4<0M26J3!a?e@)0MiRi^<tIQFOz02Mw%xPf2#Aji!_;Ib&Wa z1+Kg06sN3B#zRlV8uw!afhLW6iK%ZpH-=3Y?z;50)^gn3z2*y(^JVXm>=hjjFg8~= zG+6=>Iz9$IGNUfy+pdR&hh9KMA3S_xS;8TruEbtsil{aS{rQ2NSl>tV&JZ1!d9-;Df&L8&f0&AE(ub{i?EavM&7}a-fI*{aERva z8J!nl>|r0|7ki}Ivu!tRUg94&yf+buCeH9H_F(lFqzD4R;a(;`9UY*3S%YCDW_4Fx zM`!Y+!UURo=bzc|f;~5gME1dX59BWcSd8Rs8TH!Mr7cw48H`vGFbm{)l-^uTM49w* zN!e*DgV||s)}pW8ejYpq^vv}K1aNHObkfpin#OfZCDIfL6gXcn|L7u_Bz_ry3GJiY zqzM&DwNj<_XPD%oz)%8GkPK7jaZwZD3Ux^vpQ3nRTjI;O#OQ{^?C|{GnLg1!2L!p?*c^FNl7G-a8DZhu^ikMfzEa1{%9!*^Ei@6x) z@b4RV9Xyi!6u6>L=UJ#5?t)iw{X`}qz_oQM-FhAJ{Zb&vFPkGp>PxL7EOCh;^M@|V zg}CrmD92BO2d|McyLZDjad-y}}mrk$3bhV5WOopKTP2# z=r{E}YRY@s3p4A(^KL$u!#}s@BoL@(pn+RY|E<6l;tLfulp2dE5`FC{ls7dwXQ=}F zZ|q+Nc@*|B7XL)a^7w>ZP{+KF3zE7Mn5`i7WX%m_$#DZ48iD)#@XOWNVsB>5G?0%K zR2nn|UtN~b2v?Vc+2KaMp*!HQh5eg>f*%}JZ-b>a(gvO3d*@aPsIZOQND6;ngh#ht z7P){2pezY$;+{p?X>{|pJVuYQp!Ny&Rl_j)Ez&IZ54Sk6a!nA`Gc+q!v?@!6sFf6x^)1d1?4J`*Qk`%%m3*oCr7c3IgGs zw^z-^Q|&%1v#ju|omTA%^jh7{-x$tZ`-iwPI1WII4~U|17qi6`o9@7ztU|U!tLp}7 zdVuS{s-rD*K7Lu_W6*6YzlVq3pxx0M|K5o?@7zL|&2n!<7)P;m4Y!D{%51<6w9Vtr zF54F|;6~Z7zwk{M+WK905OZh&$6aOG0@;Up6Ivqx9;cW5?VM$S(0Ux zhaD%jHxPb|W&YavN)Rkw@(g*nBGRIsUOy}|<9J*T zl%(L@C=Ng|?L-)kLs{|9jmdI35U*1r1coBR>}nF}6)@#dp>4vXH_!^G+Y^*L-hTQM zZ1otXwEGu0Da!{=8(?$>A#6U{y-~k+FB8}<1{w?yt`_6^U^ANu+)M)EF0`%W&gORr z+!xmKP>7AjGYk_)v(Llse&x9XTV(TK6c;?=l4TWAG7>$BDdPAUE%|Kib!BpJld8SC z4#%BxC``m8uernlUQO~ZW5-jnhP2XfnER0DzZh=97t#4dO%IrKx?1_d7X_9zu_M7k zQU_EDSl|b`H#;dws%&Y;bGn!XJBGzT{~g~ES-WeK|7rv^=C=<1Kcs&BKf^MHNfx-S z>QH@udSrF2R(c+yU!g5b@6V`R<9n69mFuk8EI;84i-G(>tr`OV&!|+$+0v+0V^7MQ zp32Uco<3ZAg@+*Srwz@xe(HR-6xi&MJ^0Epb^cX*YGpu8juf%hKKLQYH5AkD-$Zz5 zHgjGaK$Z|PZ+{O4G}@!Q>-R_UU;rIVEiUKX9-Ccq4^ryVn!$ zNJe0sbDR{JrU(nJa&p!Q6I)z!s-hyMKs z*UESTd)02v{ypbpqjK9=;n;;OK0W_Z=uniVpD@;`I$@Z@ntBmw!x?5gX0`8fsVP4m z9Ew!2D7qjjUH0^k%)uY@`@EdxKx3kkQ@vSkxS}y#IV-bgbr{ z4N~~W#WN#y3+n67CrD68^gmPKgZ|H^dVzRKgrT#IvvrNioZ5^4y^)JX~^YI{!48P4QwT^FonEQSSkojdnA3{0T6> z9dT+^86gT5OaVApl_LgDSb^JzSu;kO8we!_S*a&$bB%x#>Az89M>}+KmsnG+A>{zd zPcaLhkm_hQ$CS4~Gfi>0wIw;qYV!CGY|L>6HCL9q2%I|#9RFeffhG(axQ}wCjB1lS z#6@%6BU&BKVNbIGGr@w^1bjlgl&468VgU0`-;ORVUwdPVUOt?q01FK}7A)HtXbTt9 zZJAQ?+a3raRQ36wr&e`J_VcUL$(Wgb48CJu>_SRjq=Zo4?6R5TOU*NU>uF=UGwo=o zEr>eiMxy5!);(@x2ZT|sW~nHT^L1MzTiRjEcQ$j}95IhiMI2&(6{KlGOfm<|>lfDB z4Ie|gkJLVjaqtI)ITS8p$V|%Ozlxi|#jhGSarifbgR`AXBbcc+us%_x?%LUZ&suGC zNL}Ompl%$?Z=TCN8Y-#g6q3pId|%jG)j_6WGr(tTySf_Un7q`-7ZL`g6%Ky8fsbOr z3pOt#AO85?o~$1CN4hPDg zZ@j7}oAflz;n@;i*p5IO+qneQ1WT@GC3{DHvAnDt;@%uHg!s;#tm0#N#njw zhByjAw;vnB3?8j>4!mqfMdST-9A})>b@!WtVHS2W(GAtUtnOXHqtz+Fr=0>mBR_bi z1*kUohZ^2XtZirQ;8bf)?IF4vHqc<508T{w*e$P(@J^604b4Ctmi4h6A^A!^1n-_n z?pn*~n)N$`_gB8*%>t#M?Rr0~&|taM|2uZryMBW0_j_ z%a=*UhGceO9SaTW4#MyIKkP-2PxFkS$CQ4A zdz{3HM%!^tr=&nzdZo@wHRYk*EHe{KWI%u}{K`=jMWqx}kH#kT3is~Ns{>*AuCh3p zSHZdKRAV`Jd3QoJ0jAsiA84_y>_5~p;X%n`jS>zUv@z4Fmlb)HBV4&Lynr_g#$-*N>cq`{B9Fto zopgOfv0YP_>RqBm+Et^ejaE9{c@CVhu26S!8?ip(uTLm@@y1Ftr;d;yVResA{I*_tG(|O zEVhiT_Bk!PjwTArF^o7SRNhlLNyyQn@EITqbeRG57aU-5G-QhXUB^n08`#oVs6k7Q`>P&d~f$ zeJ?qr#)*XW$NDXDo(SCRgulw3VCeTfG|&MRfjwUYAEAaij+6Mv-dr)rR+2N35~gfO zK(XMP*S}GfwdftRdoP4iq8UV|-%uN)Zn%!T^oqCo%oBDoP>1cjB6rbp0fHNPx`ERXiHzg=Il1pY_JkJWCx$gmI)0L1^TbXC}~K0bQD?@ri^XQO>Aan&Dj^u4SE}zpWh!};QeC{$r;=e zR*BezKOouO35;!Xe46bfK^|J}>zPW{e}k;^{A_^luaRVsal42^x~loCD#EB%`)9Ok zY4eu!UAQq3O)|X&K>MazLVso#`ka3cz>aP&Zboh9KfUs{T4MZ|xI1Vaa1$etI`oWL zhqaPJ6B7+5EoCOwaw(<}W811mTqajvx(&h8^TzBQBVGZ8d&ZY-!%n-_H{FdRX}ZqmZ^=%Rn$~qc z%56D4SBI4|%er&5STOvk3s0(o(h40K#Qzpr!OiW=H<69a?}mm!NXn9^AkqaLN%be< zwzL%yl%I41=`+Jf$yAWp$bN;b8GL(U`n92@3+;;;BASDPA-ll(Hp|gc!OLg0!4A7u zNI2eZ_-ZBgTfC3o?mLCrXIB^nTyzALG>dyx*P$%T0&f_G#nnl|vn7uYid(8cf=~E% zxc`lVZG95CS!&_uwoJ*1(8ZASg5g9ivKXzD!>H>qa2`fGLK+I=kO3R^gIaebEwGdmcgjQsX}l_?wnf5ikYyaM#RFFa0H`G@+aeWgxN|yrzL4^P5#z^ z(a5jr`a7+WL(($E$nHHTd@$!$Av_wZejYCIltF&=*j*1sU* z+NwDg1N~c3LC3VWel4!)r*w2fvU!n?E&OfOKz7`rRA%uGnEmGc*YU7}g_S#dr zuQZbNf(F0kBh?W1C)w)l0JHJLfeBde?1VRfM4C1EWz6aC45X(^#?#~qh>9}w6B-| zn^zI$Dq2+n|CrTwGBoK{*!cwh7s0`=;%)dG(wU3g5qZA^>T_N65e%NXQKW^7!r3L+ z;1pUcm%1X;w~RQzE&Z?!S{(ViWftP_C`nTFOl)>7aPp_oMEUO?yIz7Q-1INbF@=ivB9-Q5P@E6F@?OkbhY zC21X3tBX&aKa=hRn1lBV45LQj_+DuDkgpZ%d7 z3S1uX-BoHqqIhNr-0eRXDbcBT>L)3b8ZIvK$DEt$3x9O=ImBu6fHHs=#c?;z(h!bB*1#I-> z$9)2asSB z-Pz7%m@WDAaRM}?uuN26{3@vFfTW$-V&b(pGbpS3K*-oU%cFSAwbym$!N~+rje;iL zu?Tf0)&|U+*njOXukMZK6b1qs;_LtQ!xupzpphb!IJU@AR(1A)ZqEZdn)+U65~4Lm z*t}whI{Fj;MS`GU7ZX>Pgp`C>Wh6S%3*>u+Ew=yZf%}EPA?ZcWwiuZS#B77=Rj1+a z_Wa|dXD(9M7Rh&vT1_$3Ly0D-;bfvwNWSj96t0S{w zj*XZ`^86*}@J3x3D3c8_^v38CVfokHluV1isJ)N5Sj>rIghRQHA2!BwikCUeO8n$* z^P}Myw?AZEsX zNU2>DIuz4yWyXv{o}<&kyz_qaygZLK(j3626evF-*h~GlQ(zrqDpeq5)2Foh6@2CB zTq+}Is^PidPG?IjKCC8A(jQ2CW<2}`8;zlP zdx&d$a4VKU!nwvpaO%U2ilcJuHT;ghtX=QK76r(pF^w<=&uN$XlMm7xnhSVoc(xTo zf*`v}&q*VA3VR8E=$!mGyq>5z)+Bo5uvHaeTvttGj{d^Sd9HO%?kGVU12iUf9D%&! zV2-sRoFGmpfS0X6q;-?mF%=gy15elFEc#)v$v;|nsOQf!$!S(beM0XkppVGc*pDFQ z6shqd;;)Y4>C}l!4FE@)2*=V3eS@o?(nXmJ zO>sK8&~ZyRQ8p~{i!+xy0d8Eu@nmsJ1*MG&S*l|Xp|o|6G~9D|k2Xm~8+3e!-`mHL z1iL@s#IZZ-<@~*_vcoypaf^sQJmc8NZ1DO?7?fub)QLnDA~6nm(TSZ?NYx9|Y&~#v zTud*Y*dz=`38oLSP^IymX3}OFM8(~=U7+%*YOwQos}DBDUrbwI1#)>_EGwI|=YBct zG{h8qjB65L^+Y;QK1nF=k`mgY?Nk?eM_}X>xo;@zpp<(NBA| zW#mh%20G}+msH3L5Q{hskbYlCre%*?3dI^Fql`nQLsw$N)m+L$BA%}V_6C4bg*J2( zD1OMUzxo*;7Qtz`h{-$oH=r7q%vC5|411vK1ya#eb=x2;pC;itohQwm8^ zgVBZxDNwtt9m|M+6!i?S!JweLcBs&#pr>beQt#hnhzen`w)x%d_saeHFOYZ%LApn} zyL51neH=-y;XiQ9ypDD!ypHIZzCT*EXnD*(Va@D2ke+5?m&d@jYEy$(r(g(d5Yt_~ zR!JKBBXwY*>2S3_@Q3~vmNUn@kXU^Uj_E`=mNsNr7iglwU>L}MzyYM-@QHg&% zhCdFOrvEj*gYAiFvq2HCIa>(fbBJ2nKLwgf^9P`I+BbUIp_ zYWN%3*)CjR@o7^cN=>cBcM7xHe8k2nzaAyD?68MI$1rw&PKLgkl&IMDR=|K5!vRr( z_U~oIIWpbq(q*(2oDdTNYz%q|oqiPNFJGSSX5R2eb$oy6Wf+Fh<+ zmvu0X$P;5M6BkGWW0Nk3MF)tqrqzCJ_wfI50T1}(A^)Fu&jj_qsYC2vh%~l?4H&Pp zp^2r7|49M@Q%IqROG~qq;SNS5`Rhs<6jazj=|MWR;PPc->HRz#osp5QuI>5x`p!v` zFVy>FN)oSMUaRU^_NkJ8#$USqGc4d}oF?bi2zdAyv@P&~9W+)qkHdx^>N3x)&nQ-M zoI_!*U)-p!IB_Jb)50TCM!?$+kWS2PNDa(05W$^u9a^PthT)Uksc|=s1|G+75E9Ad zA5^iJ351UE9xDL`_G|p-+qf+}#fD;9H0GCgq1yLkRxR~@R}y3eB^AepO}4=RXtS5yYWLy83+XeXJKIw=$XeNdmGUVnfYy5b6FQ_N|$iH%@9K^M~c zdgfB=o!2js8P*C&8M*B&0%Dds42g(n6Tj<4-ivaZ4tXNb*)3|}8WU#?gn1`$JWm=BzYLY{8gqkqWO%Oaf%9tqkz3dCVB9T%bMiN4q?VQq6(il5 z!=Oc!v%XSp(&sW2c*Pk1O5YxUvf_#9l#@~6*xFh|lOuokob*L(2zP99e)@-CnI5e3 zk{LEtv0i50O`daT@$lZ&d?ALphopOQ&`3fN>5wUkF|=1(MuVs7dUt<=KzEDcX{EDR z!k@66Gp`6QMT&ISl+iq)?8407dPJftMy*ILJ1uDCSG1wRK%zz_qXw3LW5sc(K5PB0 zFRN}#TFY!Mp&WnnPEnPoR9c%GE!BA_low%Z@g?K@7Tw93!&lnEvc~vPrbkCCyrzUQ zvrv<1P3$~74V(JSvXI(!b9`Amz@P5aEVQpVrPe!#G5alH#}k~NBApuKpcg-^eS~OA z=rXX`Ex@Z8h@A$lHc)G0y;nje=tzb{uc6~VGU{I;Gb=(`9-xAdBcbgU|H=`pIC#%l zX!wR?^stA7B7QjkrKtV00MBJ9X&><&c4?B^N|^(1O|G7R;F}w{;>4gE#;r&<+plBj zh%5>9)j)cUp=dqBfQf5&c+(I>tR4NvGJo`;>Y0Os<7Cf&j()|9QZ3wiCyFtQvlBh(n~>G)RY z7tf&dc0Z#)T4$nmazKScSLBNcd9Qr~p#x(CEi86K&<(ZV#{QQ8(~_`Jp>>Tx`$o&kMU5#p?4{J=0$=xNEuUFW=rC|jOmkAv*vX}Q z*bODB!jfYSsOT%B0?9Hr5|fl+$1W`1&>~qOfz~93su+~inzo~y@aoW4VNXxNElh}| z+22Pd{F7F_mIpeJ=FL(N3rLdX&k8|#$o?|lM%{y%ZtzKiMI`#rTtDb)Fu=CDmuJ+E z%3z~*!**->%HXaG#I{9)FAS_Z<}}h=I1(l6ix2fK3qbv=*7`}Lt;C{s*04+z0W%?oF`j#GFp3}Y;K=` zi=M;0j)1?nYma0Qh69*Gr@Hkz$ZTC29)n(DF_jn-Uv!p4wQ^dbG zgw+u5s!s9{lo<2vrT~dk-I3}#kzjG8mwFFgz)LuvjF0R{>k|emrnCzVstdA?Jz)=l zjI=)3sEsW|vpmxZO*)X%G&nK2Y2O1BkBnmyXVBrRr}AA{x!B3}Y`q>(WZHlnT0PkW zQ>dseyHZh06tm%SY%az1_Bv#d2@DUar44 zC61|-$H@}|zzNkqE=DP>yWCKbxAX=T_&7Hyc|zB3VF^$odv_hFzn)tAA9OR%8lpgD)qiKeM5xH>QyE)Yzi*Vsrr+JeDu8}r;$?vc zf2AQ; zKfftH4w9t^Yfg+`KD(ds1!azA^6qMizYYHD>#>?ddW38 zQ>}a4Ix#Y&|D{o-C4jC$!zB>NQW!NuDV*y2MWbpOvAZt+?ff$T&Cg<|My2T6pX~k% z&58bb?%nwHg4WL-9twm02eH;XW>Q8dW2J=BjxV(zee;;cMLJSALQvIYzFzbe@l%M7 zR~aG}`)z?2*R|91_-hX?S8wnQCB~+wYv9Qn9GUvB44=an_ZsBs*l46^|64p-E6>(^ z|0i)_|4-t=YH0wMbnw5SM*kTFJ1G#+YbC7|CzU8er>4*M!!ePUhT-s3&@WPZ@8$42 zlL+0)#&QR9pC`l`xecKhy2nc?w#skR@!EY_ewykwJmTY9ncJoZ{!YB@&QE+Fn<4|k zx#B7UwzvBF^q*I4-8>}0P8JL7LZfkJ{yn|tSMv{>8goDg$@uC)^WYsC)eL5(glX!GH+{FiOt?8H=b1X`S;hczkT^Sp`MwWpPS8hf%2Wh z7KQCb*=@!fMsnr0w&~!ujcU?B^zt#>q<7D$BVlY~tUd}gG3Tl_Xz7vJ1V(%dRbm&( zL^_3{d6p08_j9*S+t{uanM*6#Tuva*3NhcT=pz{F{;6q_eZEYdg;awIPYmX*FITNf zGRVa7mofHRC45oZJ8y~lv}`4v}$#d9LJmY#*&KC**gMAAZmxzrfMq8&Z{N}*Zb za+9DZK;ax+vhBT0pK9L>o7u|_t!SoTKO+O#p;8g3Jd8Fp-^H`FW2QTz&bac&ho(h` zY1woCDmudAN9wnYmFr`N*QWp`=dj*$eMS}bitNqkVTH)7@inA-phcD74ZSUYH099l zXU^9VfRn7hq5Z4YH&s%?QI{we%H6D@&i4KT{27CU0?KB32l`!XoC&rd7%!QkzxXm1 zVdrT;2PWOitRl9)0GwNZ?C^NBJ**YNU6j*;A@4g)vY_mq zZ;3JFX-w%rD1QS{Jn~nU&DGSO$ik5b9%}=L55$ExD&vyo6u*peJW}4t-&an46V3Sc zgl~eE|7YjY*1AP0;70r+m@gtao($8++w9Dou~@*Ta|ZSRgE5R~j!{*O)f#7UtZ9<9 z%*R!btF_=QMnmW4z|Re>HwL)+&oG7NC#V$@cMuwxnc5(lA@!Nl*BZZfzLMCE36emS zk2veRenjp@a>SSe0mIk>P92M%1)7sVPa#>PvNt&Ud^1|i-BSADDN3lH(gDeTP!}3x z?WP$d>c>Lq_IhYO;Qs4+jDdBjV*d`Q!2U0M*R87p42dFQJ&F=!Y0<{8atrM&_>TU? zVkq=qkn~sZu~H8gY;^Ll*k19ReT$TQoNCrn@iG^zl7Z5l*@gS8&+2RL^Y!g59z+Jm z%$2=`h4WE(-of7(SNE4FXV&BQ&SPA~^qHV3FHC7Zx_@a>7BHRM*B#?QW(1EBCOnZK z%jk_f;L)1mvs7{hrp}Hez?g8>8Xkcu()&DPvQ0Ten?mG9A*68M)ZJ7KNC0V}cDU8V zJ!15a=;d|)YWhuhw8_=V8#5wicAnP>v`u;RG%p7Ait0Qd4_>o?UhA~xhh1$m>u*x2 z-n2sN!V8BC9s|{>6>s(p1}$v!tM;aPt;)-Qes-ya2U!PtA1F7L%SW_eU4*;FF@PD> zgI*|-a(GBZ1cJW7LY#L*vES~T`<#J?RUNJH%7p7^l=Az;`6YSGZ*kJU!_7@s^vB`% zm|g=FJT**J?Wh7(yAYirIjEd>ABo{1Lx7oP4=z(65ylu#0FbFk8GgT52We^p1DB*w?)6rLN!K0r+bl@lUye)rE}P z&Tq#CpRBV`LY`~ai#`(6uG@x3Et!#gZkQ0aI5L}3alIZmlSAEKIFiKOV@ zSipkdFM51(eKnTl(O+P$pH^lsUT#1iDMC26(s-Fm#`_u$CfFgsYunPgl>*E#YSAyR zh&HV=iCTkvuTEmTmg2PDl!01>CcjpK>5@Ku_q7VW5PNdzd>ML6eZ zZn7=w*kXXjKXqSaag7J6EzZ2P#stJ*@ ziAhId4H{HKFyTna{D|1~r8?4ww!IP37j#i_-qnea*u0?I>}kJN-UJ%VIK-?vhke^+ z7)0V>eY!$cXAfsYLEp8H-$mN~4;EQW9T5m1fPp4Z%f{;ib^5GFNXU$AhzgpTfOnYr zRVwKVoP?#k9xpSpnGc1eTDMSukI%Z_!7LzgxIn$Jx0TRBIcT*_%E2jR@GPY@#0l2H z$ze&yekroGwyjm?->re?Yi@vzw+)%NgWu+-*x~2rZT_RcXW;SJTo7tM)BaY-m`c8A z!vQdPRGdlFx;&DwIR1Kfbam91HcgqjHjonJtY{VCxJM#nXCROrTdY&ZB5FT2<{qw9 z$06uQmB5qQBBa8v!wYl}B6+k_DFG2UjDJ^E^O+WO_M)!6lN;+D zu<#akDNtze54PCiI#d$Z=H%iu7wRsw3GNZO*wYCX2d^n4gCg=WvtMphC`ASjATrSW z&6Cn15b$lM+ncW(AiX3qt)r0A@g$zjm)XNEyAg z6DC&h?0OU7S!(TbSun6laKnh5ujJ*%rgatE%&cq;;wIc2z-rtgsGr%f+sciSX9H^l zi<{OR3}P8>4WJQg1) z&nEJ=W92h6#qwEayGwWyXh%m4+OS>_en~|c*f3ist^*j18#K%(YTyoPm9f!lpUk_G z9u8s)?ySLPLUR8sESJJjL!yfxo5S_Yr2X<1> ze|*N{X)fK8s|Il|b_HOdi+g$epp`7xL3Dcr?jw^~^_(qD^I4jYS&;7@>{Uzl>LqJ~ z2%x4Ke%v2K5I5+oFNh`HY#@kwH0bP*VC(-QKn%nLH($@cJr{d0fWtTvL@ny{)>j7+ z!cv{RhQTwM&u7~ixhGEzpAayaKf6n%@1$42X!l}vsyR}u)MCEA#k8T8>H-t z^`9q!T^38;P$Zv;WGyFWM@r5Te<3{+?-Mj%U%dWNCv!rxW{I))2k>4zK@|>_oXxET zvn=UBiA;wU+pSs)f|VEpPnL4NXX$l!1$Jz?o7FnPKNJ`o~PXBYM;AHUH#4>dAl7Pgek6Q~pB>+?Tb9@)*w4x z31CVV@jxQiO%@!dkj>jeLGfu0n-aet`lk+{@yofiFK^`wf4QBbBxSoi-FF|IK&mCc zUPEel+d|pHkQ=!7gu||s<&JW6YY0fK)CFXT)HCap8-vIRD;G)3aMNx|NWh27GS*E# zU4pVg{cWS%NP_WXCT9m_rS{TSWtGxer3PhJU0)_ht4D^NOe$gud-8_Juv=`Rk-TTa zNRuhrl&5m*e@wYm9pQ;toxA5sIYZcxFL9U>5{})QN%!(47nCM8KytgRtAjnO3)fa( zT5F^Y!?o4YKBuL6Nx$A&Cv3(WXV8iC@ywXr(PO0shpfGJ-Ws;z>|ah9!mhj~HG>d* zx$=h6Ii48J4DGhk?7(tsdor1^LiYLve%8VMQ(60Ge_Qmfy#CpB^H+CT$z&g0gwFX2 z*%XkCaz|~IY^I@^SdtX7y|O!WJHrZixR7@9V#lu1gkz~~vYa*4PS>rM}6OgZFr zyJbXBVs5u9hv^OOW5bjqtT+rvs%uVhDyRR$e?fV*91UQT@Vyf{wBtZ;cW+l@Ag3w8 zZN^L)bbBtEC@4dGq)~Q8aKZ0!Z$)HGP_%eWVFe%(o9-8o0(TT zyK;%vmbRQYBRmx8a?Ky9^u_kbe)mTuJ(g4Vi4>+8>|^#DBkLA#%s7dM-3xa!ed|vw ze=BCa>!%;ev}a1vYDK<>nrAlb804MI7P_%7k;*3R?o_Ja{@UO@u;rnEIM}HlK8tJg zWczWJ^9;>fD0O`8rJt@$;nSzq!=z@A^id;|YfoD#+muIG-U&=EKI$!6PJGmq*RlL` zn8L@;BF(^WB)HX-Gfc$m6y{q;n2+Def7+*A4c&uvCq72r`;}q+F({F?dkd*SMwo}G z>&#^GDq_}4GC97r{d|)1iH0i9`7UQMtJhb#J1!}WwOZgf@@4Lhd?9o6Yt6%Q*2uRr ze{A61YGR*lxUsikWz;u;$RrwLQU5q@E28BBUM`4Mg{v-rndXD&)Y;vFOV|;Me?^T8 zVDuNUJ8E9Q9>En@sR6F~-B=NKYXD47pw;@8I_^ zs-|!gj4Ff0)4(S8U!#G|z>m;je_#g@Q`AxQybazQ_yK}b*iL2YA1(n?u1+EEPk(qnA%o-HlQMVCkoHsU?JuHGFRXeJ$(BkYc=e{i!qMsTY; z-i8hCD6SHMkST&>*&wbSzd&obEH1w6Ify*g(ptnvi}ABAp@%e_|Ia+q#5M8a8 z@O%+}7TZ>jFMbSFXR&D#e_xAD;)U3%qiy5(>mt6<@b^W0D_m8?KNs=sas120p0E-1 zoyAv5;|E$}MZ6gG*Eiv_CbjopcU5;*Z#KjJmLh%>yCbmZqc}Vvi;GhABz7$~*DMR1 zInrruHrH53I+u!(s($>#s9A2VKJ)mKSlYaXD7*65ke{8fYUKS`y15a)? zJI_viN*N5vQspE}4{bh&10h*nlyFg27v-jBdMHFsS&DJFIV6#?03m7QwAod_H$t+O z0A*?!m)kB@61og>PikSG&U_@=auI9Ph|+=Yxnm2hwFa#&tfRuM=)mKIbyTx%z<>+u zsPF?g>cToId<+k{f3S`UJNzoFqrxA;$6Z)Qg+GC(Tv$hiKgmb0!a6GaEGAr7M};r4 zUsqU1g|D&)Rai%bzl-m?u#O79D2rTJN5X8Imn-a!3a=N-mD7z}xdpXTWZg92X9{H` z8n|kpXpk93;2L+q3(2ccBz^l|r#P#?m$q}|d($fhnVn5)f0?^r;D_Ry#`}P4ETDB$ zjF$NXc_=XNej=Bm%0m)Xw8zq77?oJkC~*XLfz!$*l3DMP;n`_IM21}6J(MP;YB&8< zxrv^wyZ#_hO50Dtr`bwYw9w-oh)qcIq32{95bJFT$@U4^aVR7^bzmY2$-Qk8vL_a$ zC)Q6&SFAVef0J?9dln}cU8ji;$^G6Af0*+=o%deGwzkXIqW&NDA7u#8&+DQ^IoReo ze6Lc9`r1PB0Pnd(MRL>Lu&?(lA}vLEFxFeTjftjBZ=3oibI#eRueV)+?-^eFNJw6F zv?$h-h_-3i?9r=wLK0`jI48rGQ4^9;%?)NqjzxXVe=Q6md@CeL?|z0@Ygh*V;lGT8f zZn1q)e+$JC8ZIQqFG%|$meWmpT<~NW>~X<|%ivxYd~F%*b-~kRFzR#R*H6R#bLfv& zox?%R=`X~NM9tQ)8EfJHX8zZT9Ag&>5!NIFHlPd3kbP9-T~td006fflM!1SlV@r^e-l9z zJwt)rexO)UQ2bmKO2T#%u}MW@f>Pk22Gdd!pPK3Jbh~tRXEVEtAx08^k}*M}i9f&} zWxOpKqxj&<%>6p&o_lA$egFIwz#}X%ygNB*)!$e>?hZxdS?iYDw^l7zg>fKx8mPz) zl_w~!g%msylpOHHb_c>8CRvzRf9riN6R~Q=z8&(|4n`cJ_V979w??(P{tMsFq@=)+ z&V6O5tIR+)Cib|3}AveLfeYwk(myw*I9g?4tvZYL3XSB0Xf)G&(; zOft+K@+0m@9{J8*?@+j@foXD#b8{JO3(dzE*y=X9$f1AG%?NkSm z|AfKZaAgn$=~ISWW#xcj{_mn^Ss*>34U`zBH^#LkTtKma8C+z@XC$pUAZ;ct{h_LT zoTMT&aG9a#i}a;dG*5cWuv9s(WaWIQge$mOz#QhO@n{*5$6)^#_NQi|xQ6Q^p^G%B zQ$1U)iJRo5>a3JuuJX_3QMYktguGjViF_VYxW_R0oZggnKLvyS5hHfWjV%)e6zP6I z-ZCc00v5ku=G8~cmdl^8aEcq{TXdYl`hffIfiWyc=LB*;08mQ@2vR;YpvjYQY;u3W z8i>7l(Nhr=^gP*2(rq`%vYS*vEcjX;d;lLxoLHR0F#k96|IGK#=NAB6!C1h@ZugMA z$sF~DnnEt5F6C6}wsyv1XWAyI+k%*TvV?(nxx$d>73odr>mU~;+CWq3s-#Ajm?4AG z%j-O!^R3VR{bg@0gDv^MsSL7NI-6go@_htC!1%H4y{21ZNx-D_m8v`zmeh+!=g6zO zKl!{@OEk^djUL{M;ZVTo8n>t{HkG>1*QC1`js?W@O1kejFgm|@VsHd83?~#{GR*ecb+@(*b_u_mZg;Gx~s3=vf_%0E+v1sSB-X8_$q=u z74;QCEz%zfD|$$adLvr5iuITpR+YGl%|0dW4fd(Qz41gOUg7Ie!f~~}qQBQ0QTn|h zK|?)z*~+f2GXWc0k-_gtgu__ar^e!-iiH&oXE&UAcEwc=VkWsmOT>cex=>hUs?=h= zjlD6YJFGVDk175AYOH^8z46*OD764{w-5$rRa zR=v|dzTct8Lebt;HQSkHjIXW@EAhBQGE-Tvs&9^II*5S3X3eBgQC(xwh^xUwETj)K z=EJOVl9Q&%R6^647EBE*5i~vx2d#xpOo^FJpK!$ZE{MCROs0RCG>d7@WKa^F##92b zel2L&42sDRjjDR%wk>`TnnP}xX470IXZDUnr!y7l+O{pN6VO_LwtyDOG@m@VXsr@e zFcss>4!A-DV$8~*W^3C?m9#{r#k3Sw>49+_RGnir6HcO9CcAoB0#CX^ zPO2xbOm)-%TbX~HgtSIMvvISc_rZwoW3qxF_)m4N5E+@W;lbK6I#Z@I=qx7J#C?gD zgC$)vJ#tJh01+#|UO_8M=p6Ean*weo(YYCKFqYdj!_%78o^@Ix+T9Y1X)%e;%P2KX zR-y}-B;knQz)5RN-K_;9=Z2yo{k%NgjJdRvT4|mOmFT|QeDBP_=joX-fYn5nJ(>>j)uErvvsOkv{efL9;o*pgcN%Q8p zP>FeZVp@O16GZfMA)k4w9Mmb(cA+}EfQfc9c?)^q1SO`=hdy@DPC;T9lclP`L6_uF z$k=I03VQ?vg~_37=BAT^!v5Q-Tc)joy?NPA-7yf=l>=EC>P3RcK6GneOxv$?3F{jE z5fW4`HDh)&{3EJ6DJ%|XqKN5q?Mg&-l4h>;Lmhv+8ZK30l@5Xvl{ECnG$>FHsc{D( z#+>l7up%;cERNR|1>`*y4M6mLv|ohv0j8=`BVveixnS}NGn<;?2v2s>RkTv>_cKsOcx z=7WED>vho0NCzfaZvs@jeOd%*?L*L))^8@?a|#w7|K$9br$HAVrjH12J~}1$o6;8l z7_6YgdJ_={zjdG=AvH7WSR>znJIueR+=6385lP{ z5ZBd+SD4sAcOi!uWDeNw=fdr69uwY^c8LK`wFoiwfD-8s ztMwjlb7Vklt&R-rQ^Eq|yna4YA`A|iVlia^>HUi$ zK;wcRrX@KV&W+G9wn6Yq^ktcb=>CcNG+dxNOREw+2nCK)*r3GwAhJYXLBn8LHokvm zz+@H9;?IR_Q~Gh-BlM_nl!FrpVOyd@5WrAKT!d;iw`;X>cTK) z1Ux3w!!#n=9RCEa(;$z_^bkG4wESeDP`O5h3C&>cNOYz5C3=!+ef1QMYhtg;hnS$; zG(S(v^b~zPQ*RC1wIW}OEG5x5ko$i^;!W3LLaJ;9wWimho^R5#C3KAbhpGOgQkj1` zbVUdK=QHQ#P?YFf$bM*P+tmZQQIrty-=-H!=mq)?nwF@soZH-_{mn@)(RT&h%kbBT zGSH>sq?o=b?coJWHHg1L-vhnNP%KU=NK+5kP3I(uek=muRCRy;6PaG4 zpF&2jcjqOmFRpXY&+!sbbo6a;C;d`zQ%Ao-VTdQX;%WCTuWl`vtA9hk70|y!-qoTx z((X9L0&r4MO@djL!?C}oKM0lmk!jg`$Cv0&$Y^PHg_WCPknnxgr@%`t7k{C@%JgS? z6V$5DkJqI2xw@g&L4SuzL(zY3^}wbc_zaZS>ZE_tTS8ZF3tw)XOr8H0An#!Q(V|W1 zRL-=fVDs=ExjjLn;1)TaoCddoS-~q?ki9BV8$>aOJ2i*mBL2FaY%|In7a>)rF}xQG z1SvCm82mJ4FwGv8i)EHY`78-)=tx4*_(pZW$xhL$ALeN|-|OHRP#J&fG?G(BNGH#v z7X^PVLv{#*(xIzPo@FSR%aJR?YP47HGh(vU$+LM5bj5C*q($4cbcJ^EJR#?C#t>6# z(8(yJB?^%ii0Xcv7m9=m9?v}$#ZCyM@#@SKNT|G+Y3ZrqNW28GR>DrX!s$yQs z)tPZ77eL}#nd?NFXD+QD>*s$OL_gPH^mB}1cLj5i8G{@lsdkU`>h(O(%?3r4TxgS>@nM%1_$@b+#_a}g=wg6O^tiR zpw_4CQ$0#_zyt*(Mw6;ZhskX)%m&!SuW5S|&{P;Hskvoc(>DLs-RrkBHTzq3Z|i8; zvU|g(wiYKx(MEEFHSXmz&Oz8BMZ$IJf5;-@$=b@zsLPH95IJm|Hh`Bfd`N>xHAb3uwr%_4bO``GBZA zJ4|2ypv*V&O-%3aY}(S^+P>b?+8afG*X;==;yR{ZQ>z}~?;hdro^bl+2y=0?C)Aq| zu%YM#IG=yV!MC6vhGb1$aV?BN-ngpZTaBraKaBhn)_R@%QCcThxJ_K^96&mQdwyIb z{3iYcQ$+zO($@to#_fQpD;QX271EZ(pOX0wkjhvDtP6Q zW@2qx2a1{Z`7Zu!G0-st%`1S^jBzonDcus^UD$tx3sIH$UIaU4`TbgK@77R6)kM~2 z)Va^|7mE2l{-TldCN=k}R#UDo$$Srgxs*0D%?>M(u5P6=_x`66h2ge>gz_}Ls?aUb zl53L2_B75 z{D#cW@G+)KrV87W*x+Q$q>p-5=BF90p&X2Mn|PzxPdWeA@Q6c@pol@S!C+sFgSk{ zN1+PVPl0f0Fr+jKQuvF1{m0bxgE5Ld>n6 zoD2RdzbVlF#g__M!JRV_I0z!T%6;1ExX3xN(@Wc}m|m@>~42(9XXc z7)OlDW-|jaU2u|kHVI^tjHx~1$}62iLHk`kAyWyD<_x5{P?Cj_L(KG=mqUNj3F9O= zB-005tQMPWu~;w;7X`ywTy_lj_m?)J(UO(Wd9ZrY%`b zRCh?+u5=}gHcOzn9lq| z#JGaD5Jd zu6qvC7l!G95qc=#vyFey!vXIh`f8Gnr08oYIyyp61$;$bw=G4_9HHl!e0I0}2qAM0 z^7HN@@%%leCqddLCFzHQe7{?Ay=oX`<_Nt8T!H$tq0!@5|3#91JxFe#NigN>ZV9S? zBT0Yr6%CC(i2Z*U`we2hbaj&cwOjy}1N2=Jw7kf+$9Q@@$t-`6_PeDrwi;L-fn^(q zbxZbfxJ?Jy{uvw$Xomr9AEJ^GmIEm+IqC%-Kz$C#?RF%2`XJ2`#PB@E-E?o7xUX11 z6&p}Dx{HJ}xr=v~ajD@=U2r38(i@OF$z_97mXXzDl6)ks^JKR!|=iYnb zpu4EtVcR2wEq8wy()t_*T}LimgB>6P#_jNd!qDgwu+>dD>qom0?VblsMPDm>zPSD zr*mlZCA^eNZo9Qy5`x%mdxW9wyUpFh!nf+!CWqe_h z+sqS=krS_O`!H|mblU>1Td)ScIuG$hZanN9qz*UywaI69-GX)apTY7aw(ErpnJe8*kPmcY`ug!Vsw=+!H9{z7&U!nvZ+M<3aB4#F@ja8|Rk`Zha62IBv-YpYfLQ zzF{7iWOsjtv0?`mEM<00VGTKbusEcKsD_+Z9wW&%L^i9~^cA}u?&6Fdj1@#(k-OMj z80Kq*iEbF-8w2e^8+RaBGuptz&J^D~Nb|jh)g@T{L&EC(5!3KV{#bpIKRHNejqvS2 ztVKKr>PPqv`2VLpRN$ zYqi7tq)3!VWJWsV+vxOBx|bv~{TV;kN%W9J$0d4!=p9-vQQg9`sz#|yr1nvyI!8fR zfC=zQ{2itB1%UpX0UAZFES`)8i~VMjC)+oF1kmhBfJ8Pn02WQf=_r+ueQcY|O|d*L zYgvDy!^Q?^zDtdQySHe*Pzi4xrOiSgvM3i55O^!mA^?_P>0PQZH!k2&l%p&~^NoU4 zqvV_;N{jJqRGNcSj~asx5Wg2=tAT8^4CQqV*=YmdcA%v0g%ZV3a$7ghT$SAN`YbK9zDXY2X|%|;fGTWtwAj{2m9}$eiS0aEYP*Q4Y&uoj4p5El8mhHj zPj$B2z^^REXtNr!13cOx$FUK9I#9bCuKG-1qsUSz{-(D!#m~WGll;O)5oCe3+A@EB z5iw?Xcnuu=r9r9y%FBVa6n_uzKMb@Tqtf~(Y%JxZazN%FCXS#C;7K2{{1ljr8dcbFXMkE`QO+rK@hlBBMRQBO22yTtmcB1=D=$6V6}y?+9i0m z7(D}iTV~*|lbBOvqAsu#DkBz|#)* zs2KZNeHJ^?Lkv+Q;1OcDNx(Gt1g8H`O9u!%{;sOd0002&0Fx109Fu2i7n2KuEq}Ea z$6mZ`+>L^*whmYe^@1Bg6coWiq04ldPE#`%lBq7lf{)~)2rhg8A4)t^6%jd*oOAM> zFOa-{yuJb0#~Q=aczn}*u)Ey76+zEFwB5d4wcXHW zK)APNa(Cjoo^~e$0R| zxxWvkb){zvGVLf#+Ozhr*51 zm?z)Y_<87)FMl~@WauRRBWm=yR3j~}gfZMBV(IeN(u%bVJfh~0Wgz1dhFgvDU%`L4 z(q>4ND{TuF@;RhYu#iDEi#e1mnc_2 zNKpWV?M~+f#hnS3suQd{15-3LRir)vP)i303UxoZT9c21Pk&nrV3gIBKIhKkpP3Ah z5CRSl9o~6IKmrcFAbvq1_FGk)ejD%weuvetu8S3iM5`&W-QS#A2w}YbH~e z6&0%+S2nI#x!?v5F_W(|kxBNN8>2CkX?7yHyJ>ea(tj5-oAxCmLqle=sWqNTM`AI9 zoJ{4{MD|9SVv+dnrma2Kn7wI(+)VCRV)t${$uy^}#P~MdxQ5Bom)IANB_e%HXP4^O zy54R_-zh_p^uXFw${g&8$;=B%4Y;hh4+hOP_xHv!spww4o3*{YW-8SliAS_<7Z%SD zji=3IJbw~v>PN?>SfY1N6kFOb>2OT$z91TprY~Z;s`?DOJoCQ(^d@R9XL3~6T<)iG zn(iZmDw)>&9~3vJ%11M)(oa)qnwMO3mY+Q2m2b2C3AuXBUbk;%!RWnuTTId&RYDvUm@I`2vGN_ixYYq;jhubh4 z)AZ_^wn9&-TjQsCYVc7VHKJ<_HKGF6t*EZqF>#B2I+vD-7R#BYoziB|c}$gssn;fx z5r4g=LCro|B?ng)O|6e6p;;n1?5Fds4TZ45NFVM%Rdw5`w`q-R`~tdA#>3O5PE_2W zOPGvkYJ=>~PwQxL8Lg!jrdg*NXk8{6>yyLZfMqV#=Mn5HI?&)!4_$hS2DvlTuGi|L zjkFnOB4-$fvJIuWo>pbA3%j*ZyG+r+)PK4(*q1O`lbek!U;^i4Q{`%Q8_j z)fn8ce+UJ$FPKgQ`=jx`pt(QNn~n_!m*x8nH+twYfJi!Ft;IB>`g9Gj^fv00rMELJ z{WIOsAl$lzf7-pZY2NLlZVEFwQ_<^8?X0bS+Ce+zEUskQxHPxR6gHCx4*sQk-G7C- zcbjQBrPi9$J;hHE>X9{j(JvP5@sKIr1;uJg?0Ow;FpfVm)DFcu(~%@lWYIE%27DA1 zPpz4_`FLbdpd>ATRN_kPk(FXhD~gU*)`=u#Px(U*mhe1mEMCAE8y8#bkjAvKgq!{8 zW5KQH+_bh~`O0PwNfgpuQf6-^8GlU=H?;!|0fpR}Hre#K?VzP-9;kK;-Rh&8=|FDriGLjox}8bw zSZC0kaCg)I2VB)V)``QvkM8!-9RwQV&J6WM(y*g}rq))uBp;v;igiAen^s$P`#>_W zFVZ7m{}Ig78%v~2KYdi9+#Pfe=IPVM#Y%wTb$1AqksG9lR{O@`0n(8pB|*0KB}RInC4cuoEgbJBP#rj1gL8> zU|fFstRQp^{jDesZkEPAK5v2h!-x}buC+a>L@bjwmy6#=do{fa zCi+X=kYIlVr`I=saeQ$+3~E-g&tPOYI1t%u276319!y6Damj%w`+uV8fyTx0mPEWi znj8$K2O?>Fn8BsRgF6QzxG9~P!KJ~WWC8=z!$DlvVOh(9jRqSw8trz#R#03j7){}J zCk3Mb;e9eB7)e4k`yRt?dO3S|us@j?1Pr8;nUvsNN)ydS*;p~V2zDi7q2S^aYVCP~ zZ3)XnR&^dQbJRB!Tz|SawRCZOZEqR}QdAwZ8!nHgqUqp3Iz5yMHQ89$D6nW#=>myv z62!95NUNT2kkd)@cYke?fn)*WslKRr#yeITDF01KJ;bcEhPuB_G27oxUU8zl-Q`+IBWT&0&MS4~>B+9f-(& z`hg(HOY}qVu}O0R!JO^Mh-7;ai{1!S{s@da73tTAB!6=;E%~z;9hCeDz2c)E(|^dy zAg}JhJ)kMr>wj91_bL!HXYO^G{(b?Xt(kOD6!`@#g%DO;$#m&o9>ae|-2#?KCRdReiHsktLDG2V1-YYV1;!U$f#VML1@#P=4j;$b5fsI@IEKTjF##cD}J zPte1Vhp(HgtA4@iRc%kse){^9fgS=RJA`zZbVwGIXG#ELtAy>RB8D%=VdgAHU zoPT=QwOr@p8m>oBNGH~IwzRf(+L|?5#%Mxb(Y}7AhnK;ZyS8s^Snc5zmVMU^rv*P} zmNE;d8?WSM(Rh_j7lje>`50oi4__*mUz@KhWhOTz z1O}&`lHPDDZ}##zyam?0Y}?k&8(Ow|xE<3WdW-uN5_;Zh^}Os9?JSqtW+~E%X#gpr zv7fuFy34IPtKYk=x^Ovt2Ob-X4EFRz78T%O(YZ{$XAFiD5B4vG5Er(*&7iw z`%p;`w;vfwp4k7-`DvU52qRBTf`4gfJvE2(^EJF@IuS#;DH`acT~_pSoFjy6F&nTPyd>vo!<6(Y}i{zha>n?E+zxYfpafZdV;q(%N)_)79=6if| zZhhely#tYW+>E8PWm~L*!MEnv@o8Oicdm_)s1O>aavz$ zepvc_d^d(Nl3@d^K_(Rdo@|`7W6%fqgFZgMNRlg%&Gncqk`TWu6E)MZ;R3c|ux`ll za{dS(^wCWI=meXBx|sh@1Moel2&Hod*X;>9{${fM}tBR!$_^?7Tgoe8-Gcakg}i^Q4vJH zz*IZw`%#G$r<@-}Uc|`7d^+urtTX1P=jfjV2#*v$ifk=XBn#6Q6wxEGkujKDHtFFn zfrw7}1A)O$%6nY`arS9y_3=}D9QR-wjzh9t5C6U8e)fBlpT8`O{~&(_)i7(XxzSAb z4v1Ht2}I--hKW4<9DfdbZzPs6g~iOAc%pXbg(rTMpZC%I{57Uk!Rn+57nW08+!vHA zGF5LSu#tFBe*chcSbnjR+*o`Cy#`Y?9{xI5lGaUz7Dq!5{|lV55jc|e@HfHO))ze% zc=$yS!6IX65Xt8=Ht-cc7IYq34R)NgG%Ex$Lw6iu*(^?K77%pK|C zl!t$8;Te&_**7MDwLirbh^8zww(=-`)lWg1FP`@c@d0fQp(uWS9Xx}&`Ii`MCV|pb zc^xmqcJf&XzkkWU@&Y|2#StwsNi*+8zXi*{6u&F->7ua){}&u(NGf7+KmWHl<{$Vi ztW@&d$j>J&((<;(5<8n_5aMw~s8_7%KKy7MJY{Qte|yTW99EOl&nNg<>{7X5PXtti zvqZA!^;CO6t6jgwuRO|IMr)N1eDCyjL;0Zsu%H9UwtrtuMfR=OKPXhE>b0Tt-#%;y$GZP@lY)#6oa)q4Hv z+?Ln}N~RN$CDo_*E`>U3qq-D%k=g|P_C-Nt_N6>(Gj^H#!3Y^%u|J5-I*~P-@m_gp z^Q$)1F5^3Z4?WSijhP;GS&ks-QP`;j+}uxqY8y5xga%YA9))f??NHnGo3!eZm-vCf zM1P-0bpu{jtz79*VY!VZp6aZl+2K>2YNzlF`4ve&`?a06IQDv#+9f@&p73&SHyf%) zOaQvDF_HAEKHBM1y$Y6`RXyp8i`p%H1}6OEx>3KNN+eL%_|zWxnZPLz#vV1ubix1X zS#{!k^0KNDm{NgBojoyTCX<<=wAojL2!Bagdpl^hO?@pkcIu;_RSU~x)Lu|BwU5ag z&CTam!$QSAuC4=zDY!On449PJn@J043BrR1qbd1I94T>i@CEfASyof^4s)N5C+bEW zPtC1EJE1ZyxgETZQ~J z1ugwFMa!u)4bn>(j}ogpQK~05#t;Q-!{MEyG~*b}3~w2wS+!44pzaBpQ~w0bYj}dr zc}xdluf$qwBp=0!ZpfLnSz3B8`G3Z!Y0C&*jM9qmmS@R5GX7@mFST3Z-@3BJ5Vi`DzE zOf8NZY=X96r5MKV!?7O1On;xjf?vRFuY%VKmyo}`;+61iALDn>?!ow1>z^g(V|CM0 zV>H~6r5hYi(R;_}wvf}&?5ZfICp{r|l}jC_V89u0XX*XnX4eDbZ#D$njw+ntheyU= z!Ra3iI8Tr#;LOs;8nSe6xI;`9a*on{PdB?9&F(79@gOxeRJm7F(0}-iWAv$T$jH*C zVdt`dv;5pFjdWvvLkxSs4X5}hDM(|B>IK3^ayPJXq)jA8E{$XSKH~V>vYw3 zx*IyDKOS(7Q5FX>7RGrTJudo`Ykfw@Q@blmPt_iWVdlV(*J9Jv)THG~e2V-o{TTn| zPVRH$ca76rGW1z2)PJ8DgYIC1?vjH!n>0a14Wa7bIIQkEr7O`}h$GKJRZ?at707TiYU0$QwPH8pE_K3$~cM%+G;?X*+NowSQStRbLZ%K=JgnW4M2 zluzmR5!m7o5#3xL4l2EC~L;dwdy6@NHilJ7;HXEz)4623^M`Q$FD zeGPu2J@+j-YaF4#sV6|aJ%=Gn9L!JZ6y&iN!CcNls|K-Ce9s4;>%)M%A#t_g-P!|O z-$YkLBXzQ_w(bbKE7>!~Q=j4T_9Ju-ZZ*&7F0O?KWO)|CLnQ~YJP*hC2?P?F8gNy) zomXdh0e?;yZHsbkzJM!)_9@mu^U{#J4gkOnSw1)9tmNguG5|~fU(d_(>MXB0#utVI zhO-&IaBr1!*C=07j>*;uOa@sC!q)s0+9QhD=u{vmN2>`3c4UWPe7uwoGXp;qGwAlbfMg950Q7L}Yq00aW(#vMJ*?c6cOH_YH02P^re+ajx+9C8QT z&wo;_kW9lpD%RHcQ7XDphHk4|6T1UKYpC1QAu#tF<&$Ld$DaTFbraPA%_N4~ev(g`cFVak@}~lgnUbaJj+f$R{DC1%FKV zPSOk>$NeqQ!467s@=R#c4IVmbHK75~J_OoJWDsPlIlL1+?KcgtgxxqWpoTaRrt0EUMrOXgY5|Cb$VF zzMHD}dYZ{Uq*+SQSt>#S6{Xqg5t^gk#0nMi=411UG}e&(VS8Qu7(ek?xPPNIe1zuY zpyFsADk}LHKI?OZMb=Hp@-uet2K4?1>COL`ZvuD0%*Zl8s9A?Xgq@8BN)_@NW@(`6 zu{-zzUpntTfhw2dqAI8U=BeP{Haq9lVug_Fek!Zvf0AH<1Z3VA|8vMKABIcQ$dJbo zaCd@uc2@EW0S_o7*eyCF@s&`uof*Ren%Eck4v)QOJ<~>ATuB#1e zv;~u~(YCG_Z2z?YwxF^0)-^PJORO`--z&1qyl1#Z=r8|3qj7nijKQ`-&JkhDSl~z9 zk6~HaV8A)A%8(6t+Rjj!BjCZ-yq&Iq58L}mpbXo?0)G$Ew3)7*z}gx7 zN_3U$fB~9!VZeDDMm|9AqyL1NKS1|r`7wG_%g5*?EnlWrw0xa@qos8?4_S$hOaH+Q zDwpFE5>cpO4J*b;jI^l$!dT6w`R{lQ}N$sCd3)BmVbT-nHVyWN5}ZJ zu#kf{Kn_k2BLAZS*W>(~0IGhUo zC&&Z9zn`nELvZ{a=*^g#Ri9M>Y-oh1bys=ZpQ1lXu>ZYmC=50?rq0$>&RxW+c$OGb z1?^eYqL86&?td+1^ISKfGcb@(3?#cUs(e*tFwrr!1bz)s4UG$_>f@?$R4p4-=VjF@ zWR+@lz>xcXmDq7+2*Xh|LSAeV{6644o<}OV;3|Y|TlcR7I_WTfDm;PY$i4TdtHaHn z2Y7Lnaqm0xg+hE!+@f8)qT>XsN_D}Qy7+OmA*)&|)qj?(+Nvqli&nzZP^sR9eR9V! z)hQ{8x;*5@#jOeNtW@uI?CPvkS2%a!>bg5e)sj}ZwdkFy-JhbyC6~|f^-nj&_Q~yfzYH&l^QxINQV~?h;*s`W8Uxg z`RB_yd-f#v*?aHI?(EJ^W}YW+?z##!jjZzxFs@X3ORUTa9~O2xvh$`zrx#3L{6_A} z55N>q3YOJO5pnsN2;p@lYGS9dHZ&a0U;ntg3ex{l`%oy-MNIZ{YrdFe4UL9p;)TQl zzK?EWxJVFq0g$NnN=v#5%Z`vmXe|DZHd4G0| z(}dp73KE}dSMSs+ar~BR%N=4agj_kFH1Nd8e_ioWOR7zNXcDMh=y)?Rxl&?3oiZ=)-a8({Bsx{6jRjFt6&XT{VK8^H=DbnX? zp&Vc_(7qc_L7hoTR>~oCFU-v(W}~jWmY%kGuUNa>_-H|FBsZo8`Etq)T+K5aK%Til zttJo~Bq|4Qu{b${UKP#@=$WeoEz0ROy)8OyTmBUB`2|A}&a}p)KBaycmt**#R+6>g zh__4rvp61!p*vYWw(`Hm-Ki*)Cq38m1z$vos}SUTo?bXYPYRfJ#&{G<2LQa2K>vaM zBwHAA=Udo>&Y(Ihr-`#6toHtto|7706t;3(4|Qx{hFgTKrTZ?>I+pbY9}-4giB^DO zK6!hfW)kYaCHZw^SMnb}L|SH=dq;a95Ee%sF52I(IaoawAghS?9CDZq-9#PM5_YdrEEyq< z&?UPq#6}}j$%^$3aGRBcie3&6WL#tV)>6Pw`lK?feVdAW;A3g-slffPN{bIvqIptK z*BRg9ttzA#Yu0nZ(rTD<57z#(NT0#fYZRg$D(lX*)cag(7<`ZMQM zK9V>d&U2^65ksoFqXbBFW(4Pvxh=$KZ@|sAY9vH^2P<(Dlm` zKMKiv=pc^tn=U@e?2n};#(rHuK~lGM_c%ANd_s}#LOp(o+UQCQ)Z$QK33lom>r{dO(vRUV?yHg6lY3>3u^VeR*N7s z19SNOAU$!h!)pO}(FM}|ILXTLNuL)d?)3Fw(5KbbLZ*8HXU*;y&3NS4E{>DO=}%|K z{SZ(4_(4d6Q)BxXopmk&j$vG~Z(fYjY%S`@K6l+QRVI#v>X3e+Ke@AN2y>6RZu|!g6Una0(VXV*iNGI z{&4mYRC}GRcS)+BR9A|;A1^zED~9$=cu^!_86(*@J4>dfRaCAlBUB@VnUdJV3GWd;6H}#9jJ7j*jn-WwxxyMs zNsz{e;DKT9O}rFy(~ISJ7~x)iwG1$+eh0jCvA8t0G?r3ysn*H*#4w|tT@c>!T5>5c z;P=g0%=0^@oxXU4$ff7$7cvH8$3AYAeFFS#RH}X6Evr;T?0EAk`nwQ)jh87IrblAI zwj-+BwpG;uLA^1y(dpX8>?JC+4lXZpullabpaQT+58HdRO)Qn z?9|w6Dhz9_7Y)drt0GIU@TR@w2{uC$VL$)LY1)XE?fEKoQA-cai(w~<;HnUU@O@!d zuxduSz6vkJOcM{8w*cfgx#^2*K!_prdp!HKubuO-Nr92V@r!a^JVEJd@f0fNktU3! z+{vFiuJ!$j$frcIDbaj!g2$p(#jcYDgWi0avZCNfL)sd35J;nskRmDvtBq45FFv>W zj_`$^NA#e%2sb#8DzT09vm;&^RVOGsc$45C?tV(~6|c&?Wqio9z0Nyt$3*qqNz*i>FE%~M9*k?#gDwJf%C*Qb!xh$yiS8InfY2Oyc^ClmPH zQ^di)1*gpdnd*<&y0Mq?=q$E!2Wr}|HvR8~lr z43VB0Ps^#D8MNTHAil*wW2p9udT{SGwzJiFvwLc}*LR}EZow+&mhlmR#yqdg`*9K| z1x4e6(iRd(*SC(q?-sP`%!j#0v31Sd~JztmX<*JiSRUu0E8k z_GoHl<^JC0!8|r5{_CB2QuA(hvE(^GEc+l zs|405%To8#N>^vrzGZXx?-Ll-q$0fa-d}z?RkVUx$5!}Zl>KtrP~L0o5p>XmYZ9sG zoTjuq-0-zrCq46@@wL!jF<5!GXR*d6{8dqM4{M7`UZ_ctKNf51g70a_8P+SZg?X65 zjPn+r;w)eIOJF_@CfPU4U$};3yn!Bo=%Dsalu%e178G1U4>5Bm`9oc5^w5pNq9zDZ z!B9s&7aIN9DSeKj9vdH1UKc!pHv}+AHWO%3&F^EsVP%MnBD?`W;t_o@w-9F`tFllSo2PD+1XTU*?fMDrPnO1vg^w}&O{*}(Dxo2 z)&j@Y-CRNlo%?!;iL{#pb9LNh7%>AS-V!)b6(R9ay(}pSev@UN&Z-vb{Us?>rN(rD zyZrf@1zuFqp0Zi1fZFE-xb5>Fs*A#5FPYC@aTlC2^_b1?fL?22miH3bD$yNb&#Jkd z)cgNqwB?3}i>ET{Ve05D)e*<^47ZGX#i_FI=EY7r1c4lDqY|k9t)V{n?E1*Z{gb4{ zmr>P`JG@ERB5lOrT{u6%$3Ti1cE{DIM-j-__b};{;61?#jV4F$Ph6*)vBnbxyNXW9 zA@VC)aD>d>*w9o!+g%b0bE@POH$nNCnI*2Kkm-9?O)4hsZmkRD`timiPHS80*E!Vv zK0s_!h;fg?f{l^HW%SLC25lqxL(9Xe5SuT0z#*o99LBIZ1U<)>i9(05EM#PwHc-C${0Lf@-54e&IqKPtr-32f0T_6V7J~;7a2neu7;S zeJhqN-*1AQ(`a-T1{cy+vk?22yOt6u>CBWLnXIG*de?+51r=5#iJBC)THky@cOK*T z58e@@sBZ84tK*thCJJ$Op*1AGaeFxnU(|rUI`m!`8!0-lZgYk5fJulL25q|Y*6Ap5hg4#5E5)z^^V2Z&7N-9VuaGlJGn zJy|D62W(hsl=?Umhgy--eYo+H?lAjuB$dG6I1RNISvVleA4YBd1$mm z+-2uNY-HvP!7;vf<)_L(Y}C=zI#}ymh(AtbJkA3v!<3gbWlR__u>~s>N<&NLL(=+@8#*o+~K#j^8Oyy=yXIhsr?)E_On)gkd$=yyp= zir=z2!=9{_n>g2gBD`e#6_nnBsgWETnBw|WdT@JH zew&pFXr}9w#g^!Kt^9Ey9fZFc z8cn)*McMRY=X|}Sy)q!6R_DHzQ7;T@V&H%no@gVq1b`yT1u}fgu6z+QqW} z$)@~E*|Fkfk>syh*5f3$(9>rW?)MuCi>dfi#vrYm>;+rfpuk6=#Roo^pG8VU24$s+ zSH*d)5Q0TI(x2i}CO^A0WW#yOUX5p5Z^|`#yxY(ILd90i6{MO|Dlz>5s-T!%f)SYU zslHf3vWr}@Lo^ck$|q@A*q&V9G-1P&e#vZiBYTmomBdfK>b$)(y!TwbaEtFj8C5I0 z2NLpz{3W4`l$%8U3ct0$LT%v!2~Pl39eiTpRfrqvWbMMadCu%2TJQ5lY?|IRzAvv7bagc z>XUQF(PFe2-J5#xk7u?t>k&DA)HRMS)6GRSYdAOa^wZ6u5Nhe`$+`Kp>~85&JxxZ4 z$lFE7zeQzPLR0tva_a>d%yTVNo&BlbcOuA5i8QsgNCJ@I1|rer6$CfbXA}z zy+^;yBA*v+r)5o8FRLO4gXL^WEp1_DSArzLTB2lfFS~fO9kFje!F!MXP_fNX2yb`5 zvB>=m&KGSOvQJi|3t`ZQt@k|1krrQDbsmb%mM;f(>$@aS8!FG)i62dtt4U-Rvl9HG zoLQl)yHeauxPQaj9aLn)aJ5d)h>(!#o7Uu0KnN&jTSdzZvA)h4_(cLerX@Yb&^^}g z+Y)Bq&lvkjVX)$=6F}+wQ)b3086vX@qi4t??qDyC9}A85qzM9Bb!^<-_iduxZ4X4~iJJgC~ja&WQNhUr!1REn#7q z%Bh}MgTGBl9iy?Xe67IcYde*DobN4)|^ zqoN4h$}-Jn5-)|p1xnot=&zGb(6^sguGMp3%IYODWS!wP%=s5T!Ty0rfhAw+2q z{x7N$I^QTqhgQ-<ON|AVCcE4Tpw@ZUl{l!pd=QUjv(2%v~hRBmYw2 z0|30Yj>Oi0er_g*dNd2u{+HJqmGbRGkeVovDGi$87_q0ms)Vwr3zOj%DEcEBWSC8kF6Dm*c~D_* zw|?#%G_a(doA$qNZm5RMbIaS;Tr>#SAw>JPxBkBc@Ge4w{(ak{MTbS-h)~|z@Bn~^ Ww>)l_{0B@A-R&U4^o9Mo8~r~bry(!^ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 91c4fc64aa0..94c356a03a3 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.0-bin.zip networkTimeout=10000 retries=0 retryBackOffMs=500 From 3d3376584b01a6901d209527b64d9a26fbe188a9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:41:51 +0100 Subject: [PATCH 09/51] chore(deps): bump room2 from 2.8.4 to 2.8.5 (#6550) Bumps `room2` from 2.8.4 to 2.8.5. Updates `androidx.room:room-compiler` from 2.8.4 to 2.8.5 Updates `androidx.room:room-ktx` from 2.8.4 to 2.8.5 Updates `androidx.room:room-runtime` from 2.8.4 to 2.8.5 --- updated-dependencies: - dependency-name: androidx.room:room-compiler dependency-version: 2.8.5 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: androidx.room:room-ktx dependency-version: 2.8.5 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: androidx.room:room-runtime dependency-version: 2.8.5 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 3717d77fcd1..125d72bbdf6 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -37,7 +37,7 @@ otelInstrumentationAlpha = "2.29.0-alpha" otelSemanticConventions = "1.42.0" otelSemanticConventionsAlpha = "1.42.0-alpha" retrofit = "3.0.0" -room2 = "2.8.4" +room2 = "2.8.5" room3 = "3.0.0-rc01" sagp = "6.13.0" # The AGP matrix job overrides this with the VERSION_AGP env var, through each build's settings. From 842b197efea97943dee0a2601f4b12d3eed49b6e Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 11 Nov 2026 08:42:25 +0100 Subject: [PATCH 10/51] build(android): Bump AGP to 9.5.1 (#6540) Raise the default Android Gradle Plugin from 9.4.0 to 9.5.1, the latest stable release. The AGP matrix moves to 9.0.0/9.4.0/9.5.1, keeping the minimum supported version and the previous default, and the replay snapshot upload follows the new default. Lint 9.5 can't load the custom checks bundled with older androidx.lifecycle releases and reports ObsoleteLintCustomCheck, which warningsAsErrors fails on. Disable it in the affected modules; the skipped checks cover lifecycle APIs those modules don't call. Lint 9.5's new ThreadConstraint check flags ScreenshotUtils.takeScreenshot, which is safe to call from any thread because captureScreenshot posts the view draw to the UI thread. Suppress it there. Co-authored-by: Claude Opus 5.5 --- .github/workflows/agp-matrix.yml | 4 ++-- gradle/libs.versions.toml | 2 +- .../sentry/android/core/internal/util/ScreenshotUtils.java | 5 ++++- sentry-android-fragment/build.gradle.kts | 4 ++++ .../sentry-uitest-android/build.gradle.kts | 4 ++++ sentry-android-navigation/build.gradle.kts | 4 ++++ sentry-android-replay/build.gradle.kts | 4 ++++ sentry-compose/build.gradle.kts | 4 ++++ 8 files changed, 27 insertions(+), 4 deletions(-) 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/gradle/libs.versions.toml b/gradle/libs.versions.toml index 125d72bbdf6..46b82b4cb0d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -41,7 +41,7 @@ room2 = "2.8.5" room3 = "3.0.0-rc01" 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" sqlite = "2.6.2" sqliteRc = "2.8.0-alpha03" # Required by Room3 3.0.0-rc* slf4j = "1.7.30" 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 a91a8818486..776d0103d2c 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 @@ -38,7 +38,10 @@ public final class ScreenshotUtils { } // Used by Hybrid SDKs - @SuppressLint("NewApi") + // 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({"NewApi", "ThreadConstraint"}) public static @Nullable byte[] takeScreenshot( final @NotNull Activity activity, final @NotNull IThreadChecker threadChecker, diff --git a/sentry-android-fragment/build.gradle.kts b/sentry-android-fragment/build.gradle.kts index 462003eb060..80e04a4b78c 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-integration-tests/sentry-uitest-android/build.gradle.kts b/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts index d5f90f76004..784bd463c55 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 { diff --git a/sentry-android-navigation/build.gradle.kts b/sentry-android-navigation/build.gradle.kts index 2b8d3224700..af9aef5166c 100644 --- a/sentry-android-navigation/build.gradle.kts +++ b/sentry-android-navigation/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-replay/build.gradle.kts b/sentry-android-replay/build.gradle.kts index 31c3c2c17c8..8d17ff27f1e 100644 --- a/sentry-android-replay/build.gradle.kts +++ b/sentry-android-replay/build.gradle.kts @@ -62,6 +62,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-compose/build.gradle.kts b/sentry-compose/build.gradle.kts index cf0dfb7d501..6bcd20e2a36 100644 --- a/sentry-compose/build.gradle.kts +++ b/sentry-compose/build.gradle.kts @@ -116,6 +116,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 } From 42fb799ca58e5a75169c43a92e47d5f9da79d2f8 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 11 Nov 2026 08:42:52 +0100 Subject: [PATCH 11/51] fix(replay): Measure gesture batch durations on a monotonic clock (JAVA-830) (#6538) * fix(replay): Measure gesture batch durations on a monotonic clock Touch moves are batched and sent as one RRWebInteractionMoveEvent every 500ms. Both the batch timer and each position's timeOffset subtracted wall-clock readings, so a clock step corrupted them: a backward step held the batch back until the clock caught up, and dropped it if the finger lifted first; a forward step sent it at once with offsets stretched by the step. Both now come from one Stopwatch on the converter's MonotonicTicker, started with the first batched position. Without a clock step the output is unchanged. The event timestamps stay on the wall clock; they move to an AnchoredClock in v9. Fixes JAVA-830 Fixes #6523 Co-Authored-By: Claude Opus 5.5 * changelog Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../replay/gestures/ReplayGestureConverter.kt | 20 +++++--- .../gestures/ReplayGestureConverterTest.kt | 50 +++++++++++++++++++ 3 files changed, 64 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50319e4d8cd..d6940d62ce8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,7 @@ - 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)) ### Dependencies 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..91a849627ea 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 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..9e8c65bc75a 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 @@ -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() From ba3bad34667c2e9b67e5207f0a987eb9cf2c219c Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:26:52 +0100 Subject: [PATCH 12/51] fix(compose): Detect lazy layout scrolls on Compose foundation 1.10+ (#6548) Compose foundation 1.10 replaced ScrollingContainerElement with ScrollableAreaElement, so the gesture target locator no longer found LazyColumn/LazyRow/LazyGrid/Pager as scroll targets and dropped the scroll breadcrumb. Match ScrollableAreaElement and keep its class name under R8. Fixes #6547 --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Gene Wright --- CHANGELOG.md | 1 + sentry-compose/proguard-rules.pro | 1 + .../gestures/ComposeGestureTargetLocator.kt | 13 +++++++--- .../foundation/GestureModifierStubs.kt | 2 ++ .../ComposeGestureTargetLocatorTest.kt | 25 +++++++++++++++++++ 5 files changed, 39 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6940d62ce8..d3243f9991b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ ### Fixes +- 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 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)) 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/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/gestures/ComposeGestureTargetLocatorTest.kt b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/gestures/ComposeGestureTargetLocatorTest.kt index 8efdf3ebe30..407c5d2f748 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 = From 6644050d8510390abc50342b6fcb1021d3f9266b Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 11 Nov 2026 11:10:11 +0100 Subject: [PATCH 13/51] build: Upgrade Gradle to 9.9.1 (#6552) The 9.9.1 wrapper task leaves gradle-wrapper.jar unchanged, and the jar matches the official 9.9.1 wrapper checksum. Co-authored-by: Claude Opus 5.5 --- gradle/wrapper/gradle-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 94c356a03a3..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.9.0-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-bin.zip networkTimeout=10000 retries=0 retryBackOffMs=500 From 237a5fa0ff0fab5c8486fc9758f7e616afecf9fa Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 11 Nov 2026 11:16:12 +0100 Subject: [PATCH 14/51] build: Move OpenTelemetry agent test wiring into a convention plugin (#6551) The Spring Boot 2, 3 and 4 modules each copied the setup that runs the agent tests in a child JVM. The io.sentry.otel-agent-tests plugin now owns it, so the modules keep only the dependencies of their Spring Boot line. Fixes #6378 Fixes JAVA-801 Co-authored-by: Claude Opus 5.5 --- .cursor/rules/e2e_tests.mdc | 9 +- build-logic/build.gradle.kts | 4 + .../io/sentry/gradle/OtelAgentTestsPlugin.kt | 107 ++++++++++++++++++ .../build.gradle.kts | 4 +- sentry-spring-boot-4/build.gradle.kts | 66 +---------- sentry-spring-boot-jakarta/build.gradle.kts | 66 +---------- sentry-spring-boot/build.gradle.kts | 66 +---------- 7 files changed, 138 insertions(+), 184 deletions(-) create mode 100644 build-logic/src/main/kotlin/io/sentry/gradle/OtelAgentTestsPlugin.kt 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/build-logic/build.gradle.kts b/build-logic/build.gradle.kts index d11d2dcdc3f..2c48083cdce 100644 --- a/build-logic/build.gradle.kts +++ b/build-logic/build.gradle.kts @@ -46,5 +46,9 @@ gradlePlugin { 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/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/sentry-opentelemetry/sentry-opentelemetry-agent/build.gradle.kts b/sentry-opentelemetry/sentry-opentelemetry-agent/build.gradle.kts index 81e690fbe0a..67c9feea2d6 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-agent/build.gradle.kts +++ b/sentry-opentelemetry/sentry-opentelemetry-agent/build.gradle.kts @@ -108,7 +108,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() } diff --git a/sentry-spring-boot-4/build.gradle.kts b/sentry-spring-boot-4/build.gradle.kts index f1c3d0cc72b..f8488605269 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) @@ -163,22 +164,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) @@ -201,8 +187,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 @@ -337,9 +321,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) @@ -351,7 +334,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 @@ -389,37 +371,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( @@ -441,10 +392,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-jakarta/build.gradle.kts b/sentry-spring-boot-jakarta/build.gradle.kts index cfee8ecb5cf..55fd0d6af17 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) @@ -146,22 +147,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) @@ -182,8 +168,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 @@ -311,9 +295,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) @@ -324,42 +307,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( @@ -379,10 +330,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/build.gradle.kts b/sentry-spring-boot/build.gradle.kts index 18c60978234..09092b9d7c1 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) @@ -141,22 +142,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) @@ -173,8 +159,6 @@ dependencies { "agentFixtureImplementation"(libs.springboot.starter.webflux) "agentFixtureImplementation"(libs.spring.kafka2) "agentFixtureRuntimeOnly"(libs.hsqldb) - - otelAgentJar(projects.sentryOpentelemetry.sentryOpentelemetryAgent) } testing { @@ -256,9 +240,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) @@ -269,42 +252,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( @@ -324,10 +275,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() } From 1c8f6950ccf2b9662dc1a8f1a0d90a1ae0b00542 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:23:11 +0000 Subject: [PATCH 15/51] chore(deps): bump ktorClient from 3.0.0 to 3.6.1 (#6478) * chore(deps): bump ktorClient from 3.0.0 to 3.6.1 Bumps `ktorClient` from 3.0.0 to 3.6.1. Updates `io.ktor:ktor-client-core` from 3.0.0 to 3.6.1 - [Release notes](https://github.com/ktorio/ktor/releases) - [Changelog](https://github.com/ktorio/ktor/blob/3.6.1/CHANGELOG.md) - [Commits](https://github.com/ktorio/ktor/compare/3.0.0...3.6.1) Updates `io.ktor:ktor-client-java` from 3.0.0 to 3.6.1 - [Release notes](https://github.com/ktorio/ktor/releases) - [Changelog](https://github.com/ktorio/ktor/blob/3.6.1/CHANGELOG.md) - [Commits](https://github.com/ktorio/ktor/compare/3.0.0...3.6.1) --- updated-dependencies: - dependency-name: io.ktor:ktor-client-core dependency-version: 3.6.1 dependency-type: direct:production update-type: version-update:semver-minor - dependency-name: io.ktor:ktor-client-java dependency-version: 3.6.1 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * fix(ktor): [Ktor 3.6 2] Preserve Ktor 3.0 runtime compatibility (#6517) * fix(ktor): Preserve Ktor 3.0 runtime compatibility Avoid inlining Ktor 3.6's AttributeKey factory. The inlined code references a TypeInfo constructor unavailable in older Ktor 3.x runtimes. Construct TypeInfo explicitly through its stable two-argument constructor instead. * test(ktor): [Ktor 3.6 3] Add Ktor 3.0 compatibility suite (#6520) * test(ktor): Add Ktor 3.0 compatibility suite Compile the production integration against the catalog Ktor version while compiling and running the existing tests against Ktor 3.0.0. Add the compatibility suite to check so inline API binary incompatibilities fail CI. * test(ktor): Simplify Ktor 3.0 suite configuration Use Ktor's enforced platform to pin all compatibility test artifacts to 3.0.0 instead of maintaining a custom resolution strategy. Reuse the standard test source directories so the suite follows source changes. Co-Authored-By: Claude * Update sentry-ktor-client/build.gradle.kts Co-authored-by: Nelson Osacky --------- Co-authored-by: Claude Co-authored-by: Nelson Osacky --------- Co-authored-by: Claude Co-authored-by: Nelson Osacky --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Alexander Dinauer Co-authored-by: Claude Co-authored-by: Nelson Osacky --- gradle/libs.versions.toml | 2 +- sentry-ktor-client/build.gradle.kts | 25 +++++++++++++++++++ .../ktorClient/SentryKtorClientPlugin.kt | 9 +++++-- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 46b82b4cb0d..648f6a4bccf 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -21,7 +21,7 @@ jetbrainsCompose = "1.6.11" kotlin = "2.3.21" kotlin-compatible-version = "1.9" ksp = "2.3.13" -ktorClient = "3.0.0" +ktorClient = "3.6.1" logback = "1.2.9" log4j2 = "2.26.1" nopen = "1.0.1" diff --git a/sentry-ktor-client/build.gradle.kts b/sentry-ktor-client/build.gradle.kts index a204e71ff91..6329db9c3dc 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 0e4538fb418..0109aeb9fbc 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() From 40c9b1efd85a744d3cabf3952b406bdfacd1b944 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 11 Nov 2026 12:29:32 +0100 Subject: [PATCH 16/51] ref(android): Fix Error Prone warnings in sentry-android-core (#6499) * ref(android): Fix Error Prone warnings in sentry-android-core Error Prone never ran on sentry-android-core. Enabling it reports 59 warnings outside Javadoc, which fail the build under -Werror. - Suppress FutureReturnValueIgnored, JavaUtilDate, and ReferenceEquality where identity is intended, as the sentry module does. - Keep the AnrProfilingIntegration updater a field, since removeCallbacks needs the instance that was posted, and suppress UnnecessaryLambda there. - Read the ANR thread dump and the app start profiling config as UTF-8, Android's default charset. - Remove unused fields and parameters, add missing @Override, make long-to-double conversions explicit, and narrow members that are effectively private or protected in a final class. - Explain the two catch blocks that ignore their exception. Co-Authored-By: Claude Opus 5.5 * ref(android): Fix the Error Prone warnings only main has - ANRWatchDog.monotonicTicker is never read (#6041), since the ticker lambda captures the constructor parameter. Remove the field and keep the parameter. - ActivityFramesTracker.lock is protected in a final class; make it package-private. - LifecycleWatcher reads the session start Date to seed the session window; suppress JavaUtilDate there, as the other Date uses are. Co-Authored-By: Claude Opus 5.5 * ref(android): Keep the default charset reads as they were Android's default charset is always UTF-8, so DefaultCharset is disabled for the Android modules in #6493 instead of being fixed here. Co-Authored-By: Claude Opus 5.5 * ref(android): Drop the UnnecessaryLambda suppressions #6493 disables UnnecessaryLambda for the Android modules, so the suppressions on the ANRWatchDog and AnrProfilingIntegration fields are redundant. Co-Authored-By: Claude Opus 5.5 * ref(android): Drop the updater field comment Co-Authored-By: Claude Opus 5.5 * docs(android): Make the local-class method comment a plain comment Error Prone's NotJavadoc flags Javadoc on methods of local classes, which #6537 added in AndroidConnectionStatusProvider. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../src/main/java/io/sentry/android/core/ANRWatchDog.java | 3 --- .../io/sentry/android/core/ActivityFramesTracker.java | 2 +- .../sentry/android/core/ActivityLifecycleIntegration.java | 1 + .../io/sentry/android/core/AndroidContinuousProfiler.java | 2 ++ .../java/io/sentry/android/core/AndroidFatalLogger.java | 8 ++------ .../sentry/android/core/AndroidLoggerBatchProcessor.java | 1 + .../sentry/android/core/AndroidMetricsBatchProcessor.java | 1 + .../io/sentry/android/core/AndroidOptionsInitializer.java | 2 +- .../main/java/io/sentry/android/core/AnrIntegration.java | 4 ++-- .../java/io/sentry/android/core/AnrV2Integration.java | 1 + .../android/core/AppComponentsBreadcrumbsIntegration.java | 1 + .../android/core/ApplicationExitInfoEventProcessor.java | 2 ++ .../main/java/io/sentry/android/core/ContextUtils.java | 1 + .../io/sentry/android/core/CurrentActivityHolder.java | 2 ++ .../java/io/sentry/android/core/EnvelopeFileObserver.java | 2 +- .../android/core/EnvelopeFileObserverIntegration.java | 1 + .../io/sentry/android/core/FeedbackShakeIntegration.java | 4 ++++ .../main/java/io/sentry/android/core/Installation.java | 3 +-- .../java/io/sentry/android/core/InternalSentrySdk.java | 1 + .../java/io/sentry/android/core/LifecycleWatcher.java | 1 + .../src/main/java/io/sentry/android/core/LoadClass.java | 3 +++ .../io/sentry/android/core/MemoryLimiterIntegration.java | 1 + .../java/io/sentry/android/core/NativeEventCollector.java | 1 + .../android/core/NetworkBreadcrumbsIntegration.java | 5 +---- .../sentry/android/core/PerfettoContinuousProfiler.java | 2 ++ .../java/io/sentry/android/core/PerfettoProfiler.java | 1 + .../android/core/PerformanceAndroidEventProcessor.java | 3 --- .../main/java/io/sentry/android/core/SentryAndroid.java | 3 +-- .../io/sentry/android/core/SentryUserFeedbackForm.java | 3 +++ .../android/core/SystemEventsBreadcrumbsIntegration.java | 6 +++++- .../java/io/sentry/android/core/TombstoneIntegration.java | 1 + .../sentry/android/core/anr/AnrProfilingIntegration.java | 1 + .../core/internal/gestures/SentryGestureListener.java | 1 + .../core/internal/modules/AssetsModulesLoader.java | 1 + .../io/sentry/android/core/internal/threaddump/Lines.java | 5 +++-- .../internal/util/AndroidConnectionStatusProvider.java | 3 ++- .../core/internal/util/SentryFrameMetricsCollector.java | 3 +++ .../java/io/sentry/android/core/performance/TimeSpan.java | 4 ++-- 38 files changed, 59 insertions(+), 31 deletions(-) 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/ActivityFramesTracker.java b/sentry-android-core/src/main/java/io/sentry/android/core/ActivityFramesTracker.java index 3895819fc94..8aa737f7192 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ActivityFramesTracker.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ActivityFramesTracker.java @@ -40,7 +40,7 @@ public final class ActivityFramesTracker { new WeakHashMap<>(); private final @NotNull MainLooperHandler handler; - protected @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); + @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); private final @NotNull LazyEvaluator androidXAvailable; 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 505bb84ea2c..faf672ee009 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 @@ -496,6 +496,7 @@ void applyScope(final @NotNull IScope scope, final @NotNull ITransaction transac } @VisibleForTesting + @SuppressWarnings("ReferenceEquality") void clearScope(final @NotNull IScope scope, final @NotNull ITransaction transaction) { scope.withTransaction( scopeTransaction -> { 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 67720e121ae..cb54723d8e1 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 @@ -335,6 +335,7 @@ private void stop(final boolean restartProfiler) { } } + @Override public void reevaluateSampling() { shouldSample = true; } @@ -373,6 +374,7 @@ public void close(final boolean isTerminating) { return ProfileRecordingState.UNKNOWN; } + @SuppressWarnings("FutureReturnValueIgnored") private void sendChunks(final @NotNull IScopes scopes, final @NotNull SentryOptions options) { try { options 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/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 8ba216386b2..73f04af149c 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 @@ -502,7 +502,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/AnrIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AnrIntegration.java index 275914e3fe2..eb5a27c4a5e 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 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 23bce6d1398..c930bc96afb 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 @@ -64,6 +64,7 @@ public AnrV2Integration(final @NotNull Context context) { @SuppressLint("NewApi") // we do the check in the AnrIntegrationFactory @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..6dfcb888f3f 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 @@ -169,6 +169,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/ApplicationExitInfoEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java index 80da05967ea..a82a6de5db8 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 @@ -243,6 +243,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); @@ -933,6 +934,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 de85d715413..b71c3628c6e 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 @@ -521,6 +521,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 d505a862f34..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 @@ -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/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..7966ca98d99 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"); 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..43341432c5f 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 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 f0dcc8121be..5400478cbfa 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 @@ -409,6 +409,7 @@ private static void addTimeSpanToSerializedSpans(TimeSpan span, List if it's available, or null */ + @Override public @Nullable Class loadClass(final @NotNull String clazz, final @Nullable ILogger logger) { return delegate.loadClass(clazz, logger); } + @Override public boolean isClassAvailable(final @NotNull String clazz, final @Nullable ILogger logger) { return delegate.isClassAvailable(clazz, logger); } + @Override public boolean isClassAvailable( final @NotNull String clazz, final @Nullable SentryOptions options) { return delegate.isClassAvailable(clazz, options); 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/NetworkBreadcrumbsIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/NetworkBreadcrumbsIntegration.java index 2259f4d4a6d..ae208d49bdb 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( @@ -237,7 +234,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 e229744bc8a..e41bbbf28fb 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 @@ -527,12 +527,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, 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 2f9522194c6..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 @@ -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 142bb1f4752..503bd1d856b 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 @@ -41,13 +41,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 ActivityFramesTracker activityFramesTracker; 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/SentryAndroid.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java index 82916a248e6..bdfb1646a00 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 @@ -48,8 +48,7 @@ public final class SentryAndroid { private static final String FRAGMENT_CLASS_NAME = "androidx.fragment.app.FragmentManager$FragmentLifecycleCallbacks"; - protected static final @NotNull AutoClosableReentrantLock staticLock = - new AutoClosableReentrantLock(); + static final @NotNull AutoClosableReentrantLock staticLock = new AutoClosableReentrantLock(); private SentryAndroid() {} 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 2950e04b257..4be90baad56 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 @@ -179,6 +179,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 +187,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 +195,7 @@ public void onActivityPaused(final @NotNull Activity activity) { } @Override + @SuppressWarnings("ReferenceEquality") public void onActivityDestroyed(final @NotNull Activity activity) { if (activity == activityRef.get()) { stopShakeDetection(); 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..402a0b35cac 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 @@ -124,6 +124,7 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions } } + @SuppressWarnings("FutureReturnValueIgnored") private void registerReceiver( final @NotNull IScopes scopes, final @NotNull SentryAndroidOptions options) { @@ -196,7 +197,10 @@ 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() { if (options == null) { return; 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 b2fc0221a28..03e7c36b565 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 @@ -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( 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 946541acc4e..c101ef92adf 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 @@ -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); 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..12ca130be9e 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 @@ -314,6 +314,7 @@ void stopTracing(final @NotNull SpanStatus status) { } @VisibleForTesting + @SuppressWarnings("ReferenceEquality") void clearScope(final @NotNull IScope scope) { scope.withTransaction( transaction -> { 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..ea94ea8e262 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); 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/util/AndroidConnectionStatusProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java index fe7db65c621..256cf88e7b0 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 @@ -386,7 +386,7 @@ public void onCapabilitiesChanged( } } - /** + /* * Caches the capabilities and notifies observers. * *

No-ops unless the incoming {@code networkCapabilities} differ from the stored ones @@ -1091,6 +1091,7 @@ ConnectionSnapshot withCapabilities( } } + @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/SentryFrameMetricsCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java index b3b31f00f7f..697bf2a5a60 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 @@ -272,6 +272,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()) { @@ -375,6 +376,7 @@ private void stopTrackingWindow(final @NotNull Window window) { }); } + @SuppressWarnings("ReferenceEquality") private void setCurrentWindow(final @NotNull Window window) { if (currentWindow != null && currentWindow.get() == window) { return; @@ -425,6 +427,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/TimeSpan.java b/sentry-android-core/src/main/java/io/sentry/android/core/performance/TimeSpan.java index 105726e5f21..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 @@ -99,7 +99,7 @@ public long getStartTimestampMs() { /** Returns the start timestamp of this measurement, unix time, in seconds. */ public double getStartTimestampSecs() { - return DateUtils.millisToSeconds(startUnixTimeMs); + return DateUtils.millisToSeconds((double) startUnixTimeMs); } /** @@ -120,7 +120,7 @@ public long getProjectedStopTimestampMs() { * @see #getProjectedStopTimestampMs() */ public double getProjectedStopTimestampSecs() { - return DateUtils.millisToSeconds(getProjectedStopTimestampMs()); + return DateUtils.millisToSeconds((double) getProjectedStopTimestampMs()); } /** From 072775b49cc11668b558df71091ca66e08d72152 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 11 Nov 2026 12:30:31 +0100 Subject: [PATCH 17/51] fix(android): Resolve NullAway findings in sentry-android-core (#6497) * fix(android): Resolve NullAway findings in sentry-android-core NullAway never ran on sentry-android-core. Enabling it reports 32 errors. Most are fields and return types that are nullable but not annotated, and fields NullAway cannot see as checked because a check happens in a different scope (a lambda, another method) than the dereference. - Annotate the nullable fields and return types, including ViewHierarchyNode.setType and UiElement.equals in the sentry module. - Read options once in lambdas, and pass scopes and options to createStandaloneAppStartTransaction, whose callers already check them. - Compute the device family once instead of through a LazyEvaluator, whose evaluator must not return null. - Create the system events HandlerThread in the branch that uses it, inside the existing try. Co-Authored-By: Claude Opus 5.5 * ref(android): Build the system events IntentFilter where it is registered The filter was a nullable field, built on the first registration and cleared in close(). It only depends on the final actions array, so build it in the registration task instead. That leaves nothing nullable to track. Co-Authored-By: Claude Opus 5.5 * fix(android): Check options before finishing the app start span finishAppStartSpan passed the nullable options field to getAppStartTimeSpanWithFallback, which NullAway reports on main. The end time is only used when performance is enabled, which register() sets together with options, so return early when either is unset. Co-Authored-By: Claude Opus 5.5 * fix(android): Annotate the view hierarchy byte array as nullable @Nullable byte[] annotates the element type for TYPE_USE annotations, so Kotlin saw ByteArray instead of ByteArray?. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../core/ActivityLifecycleIntegration.java | 17 ++++++++----- .../java/io/sentry/android/core/AppState.java | 4 +-- .../core/DefaultAndroidEventProcessor.java | 8 +++--- .../core/FeedbackShakeIntegration.java | 1 + .../SystemEventsBreadcrumbsIntegration.java | 25 ++++++++----------- .../core/ViewHierarchyEventProcessor.java | 2 +- .../android/core/anr/AnrProfileManager.java | 2 +- .../AndroidViewGestureTargetLocator.java | 2 +- .../internal/threaddump/ThreadDumpParser.java | 2 +- .../internal/tombstone/TombstoneParser.java | 1 + .../core/AndroidLoggerBatchProcessorTest.kt | 4 +-- .../core/AndroidMetricsBatchProcessorTest.kt | 4 +-- .../core/SessionTrackingIntegrationTest.kt | 2 +- .../SystemEventsBreadcrumbsIntegrationTest.kt | 10 ++++---- .../core/anr/AnrProfilingIntegrationTest.kt | 6 ++--- .../AndroidConnectionStatusProviderTest.kt | 2 +- .../sentry/internal/gestures/UiElement.java | 2 +- .../io/sentry/protocol/ViewHierarchyNode.java | 2 +- 18 files changed, 49 insertions(+), 47 deletions(-) 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 faf672ee009..0c3b7d8d5ff 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 @@ -186,7 +186,7 @@ private void stopPreviousTransactions() { private void startTracing(final @NotNull Activity activity) { WeakReference weakActivity = new WeakReference<>(activity); - if (scopes != null && !isRunningTransactionOrTrace(activity)) { + if (scopes != null && options != null && !isRunningTransactionOrTrace(activity)) { if (!performanceEnabled) { activitiesWithOngoingTransactions.put(activity, NoOpTransaction.getInstance()); if (options.isEnableAutoTraceIdGeneration()) { @@ -309,7 +309,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(); @@ -359,7 +359,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( @@ -978,13 +978,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(options) .getProjectedStopTimestamp(); - if (performanceEnabled && appStartEndTime != null) { + if (appStartEndTime != null) { finishSpan(appStartSpan, appStartEndTime); if (appStartTransaction != null && !appStartTransaction.isFinished()) { appStartTransaction.finish(SpanStatus.OK, appStartEndTime); @@ -1033,7 +1036,7 @@ private void onHeadlessAppStart() { } final @NotNull ITransaction transaction = - createStandaloneAppStartTransaction(startTime, null, false); + createStandaloneAppStartTransaction(scopes, options, startTime, null, false); transaction.finish(SpanStatus.OK, endTime); } @@ -1044,6 +1047,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) { @@ -1122,7 +1127,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/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/DefaultAndroidEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java index c7ea0e27e4f..75776dee6ae 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, @@ -241,7 +239,7 @@ private void setDevice(final @NotNull SentryLogEvent event) { new SentryLogEventAttributeValue(SentryAttributeType.STRING, Build.MODEL)); event.setAttribute( "device.family", - new SentryLogEventAttributeValue(SentryAttributeType.STRING, deviceFamily.getValue())); + new SentryLogEventAttributeValue(SentryAttributeType.STRING, deviceFamily)); } catch (Throwable e) { options.getLogger().log(SentryLevel.ERROR, "Failed to retrieve device info", e); } @@ -269,7 +267,7 @@ private void setDevice(final @NotNull SentryMetricsEvent event) { new SentryLogEventAttributeValue(SentryAttributeType.STRING, Build.MODEL)); event.setAttribute( "device.family", - new SentryLogEventAttributeValue(SentryAttributeType.STRING, deviceFamily.getValue())); + new SentryLogEventAttributeValue(SentryAttributeType.STRING, deviceFamily)); } catch (Throwable e) { options.getLogger().log(SentryLevel.ERROR, "Failed to retrieve device info", e); } 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 43341432c5f..3f042e08209 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 @@ -278,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 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 402a0b35cac..ae57b75ab4a 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 @@ -66,8 +66,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 @@ -147,17 +146,9 @@ private void registerReceiver( } receiver = new SystemEventsBroadcastReceiver(scopes, options); - if (filter == null) { - filter = new IntentFilter(); - for (String item : actions) { - filter.addAction(item); - } - } - if (customHandler == null && handlerThread == null) { - handlerThread = - new HandlerThread( - "SystemEventsReceiver", Process.THREAD_PRIORITY_BACKGROUND); - handlerThread.start(); + 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 @@ -168,6 +159,12 @@ private void registerReceiver( if (customHandler != null) { handler = customHandler; } else { + if (handlerThread == null) { + handlerThread = + new HandlerThread( + "SystemEventsReceiver", Process.THREAD_PRIORITY_BACKGROUND); + handlerThread.start(); + } handler = new Handler(handlerThread.getLooper()); } ContextUtils.registerReceiver(context, options, receiver, filter, handler); @@ -202,6 +199,7 @@ private void registerReceiver( "FutureReturnValueIgnored" }) // older AGP versions do not support method references private void scheduleUnregisterReceiver() { + final @Nullable SentryAndroidOptions options = this.options; if (options == null) { return; } @@ -237,7 +235,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(); } 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..fb56d1778fb 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 @@ -125,7 +125,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, 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 62fce10c84d..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 @@ -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/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/threaddump/ThreadDumpParser.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/threaddump/ThreadDumpParser.java index e6c9430fa21..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 @@ -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 4444e4981e7..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 @@ -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/test/java/io/sentry/android/core/AndroidLoggerBatchProcessorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidLoggerBatchProcessorTest.kt index 18bf67cd11c..8735d5bcebd 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 @@ -96,7 +96,7 @@ class AndroidLoggerBatchProcessorTest { val sut = fixture.getSut() sut.close(false) - assertTrue(AppState.getInstance().lifecycleObserver.listeners.isEmpty()) + assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) } @Test @@ -104,6 +104,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 a965c066279..199533905e4 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 @@ -95,7 +95,7 @@ class AndroidMetricsBatchProcessorTest { val sut = fixture.getSut() sut.close(false) - assertTrue(AppState.getInstance().lifecycleObserver.listeners.isEmpty()) + assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) } @Test @@ -103,6 +103,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/SessionTrackingIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SessionTrackingIntegrationTest.kt index ef920e1d7fe..6c8eaa4d851 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 @@ -119,7 +119,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/SystemEventsBreadcrumbsIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegrationTest.kt index 2505b6f7f7d..60282aca26d 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,7 +387,7 @@ class SystemEventsBreadcrumbsIntegrationTest { sut.register(fixture.scopes, fixture.options) assertTrue( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration } ) @@ -401,7 +401,7 @@ class SystemEventsBreadcrumbsIntegrationTest { sut.register(fixture.scopes, fixture.options) assertFalse( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration } ) @@ -414,7 +414,7 @@ class SystemEventsBreadcrumbsIntegrationTest { sut.register(fixture.scopes, fixture.options) assertTrue( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration } ) @@ -422,7 +422,7 @@ class SystemEventsBreadcrumbsIntegrationTest { sut.close() assertFalse( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration } ) @@ -447,7 +447,7 @@ class SystemEventsBreadcrumbsIntegrationTest { shadowOf(Looper.getMainLooper()).idle() 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/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/internal/util/AndroidConnectionStatusProviderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProviderTest.kt index 56cf8f4e0ba..9c209006cb6 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 @@ -836,7 +836,7 @@ class AndroidConnectionStatusProviderTest { connectionStatusProvider.onBackground() assertFalse( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration } ) 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/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; } From 0fb4971059c99a71dd7f004750cb0dad0c94b760 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 11 Nov 2026 13:37:35 +0100 Subject: [PATCH 18/51] build: Stop logging passed tests and test output to the console (#6554) Every passing test printed a PASSED line plus its stdout/stderr, which buried the failures in CI logs. The console now shows only skipped and failed tests. Test output is still in the HTML and XML test reports. Co-authored-by: Claude Opus 5.5 --- build.gradle.kts | 2 -- 1 file changed, 2 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index ed939bea272..ef0248024d5 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -36,11 +36,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 ) } From 00a30a786b07a7f1380ec5610b087f5d4e6b1999 Mon Sep 17 00:00:00 2001 From: J-P Nurmi Date: Wed, 11 Nov 2026 14:59:25 +0100 Subject: [PATCH 19/51] feat(android): Add experimental out-of-process crash reporting (#6347) * feat(android): Add service-managed NDK crash daemon Run the NDK crash daemon from an isolated Android service process so it can release the crashing app, merge the resulting tombstone, and send the enriched envelope before shutdown. * Update CHANGELOG.md * fix(android): Narrow exception handling in the NDK crash service Replace the broad `Throwable` catches in `SentryNdkCrashService` with the exceptions the guarded code can throw, and restore the interrupt flag when the service bind is interrupted. * fix(android): Stop the NDK crash service when its daemon exits The service was started with `startService` but never stopped, so its process kept running after `Sentry.close()` or after the app process died. Call `stopSelf` with the start ID that was current when the worker started, so a newer start from a relaunched app is not stopped. * fix(android): Match the NDK crash service stop to its own start A new service process receives `onBind` before `onStartCommand`, so a worker started from the binder configuration could capture a stale start ID and never stop the service. Tag each start with its shared memory path and stop only when the latest start belongs to the exiting worker. * fix(android): Write the NDK tombstone marker after a successful send The marker was written as soon as the merged envelope existed. If the send then failed with a network error, the daemon discarded the envelope and the next launch skipped the tombstone as already reported, so the crash was lost. Write the marker only once the send succeeds. * fix(android): Bind the NDK crash service for the app's lifetime `startService` throws when the app starts in the background, and the started service stopped about a minute after the app left the foreground, so a later crash found no daemon. Native init then fell back to fork/exec, which cannot exec `libsentry-crash.so` from inside the APK with default packaging, and stalled startup for 10 s. Bind the service with `BIND_AUTO_CREATE` and keep the binding until `SentryNdk.close()`, so the service process keeps the app's importance and is not frozen. Let crash processing continue after `onDestroy`, which runs as soon as a crashed app's binding goes away. Fail NDK init instead of falling back to fork/exec when the service is unavailable: below API 30, without a context, or when binding or configuring fails. Move the inproc `SentryNdkTest` to inproc-only test sources, since outproc init now requires a context. * fix(android): Match NDK tombstones by the app's pid The crash service picked the native crash exit info closest to the event's timestamp and ignored its pid. In a crash loop, the first poll can run before the current crash has an exit info, and the previous crash's tombstone was merged instead. Skip exit infos of other pids. The worker captures the pid when it starts, so a later configure call cannot change it. * fix(android): Start an NDK crash daemon for each relaunch When the app relaunched while the previous daemon was still sending its crash, or before it noticed that its process was gone, the new config was stored but no worker started, and the old worker's cleanup then cleared it. The relaunched app's next crash waited 10 s in the handler and was lost, and its descriptors leaked. Keep the per-app daemon state in a config owned by its worker, and start a worker for each config right away. The old daemon is past crash processing or only waiting for its process to go away, so the two share only process-wide native state such as the logger. * ci(temp): Publish sentry-native-ndk-outproc to Maven Local `sentry-android-ndk-outproc` depends on `io.sentry:sentry-native-ndk-outproc`, which is not on Maven Central yet. Build it from the sentry-native feature branch and publish it to Maven Local so the Build job can resolve it. TODO: Revert. This is temporary until sentry-native publishes the artifact. * fix(android): Wait for the NDK tombstone outside the send budget The tombstone wait and the send shared `shutdownTimeoutMillis`, so a slow tombstone left the send no time at all. Wait for the app's exit info instead. The app exits right after debuggerd writes its tombstone, so the wait ends when the tombstone is there, capped at the 30 s match tolerance. Stop early when the app did not crash natively or the tombstone does not parse. Give the send the full `shutdownTimeoutMillis`, and write the marker for a merged envelope that was sent or kept for the next launch. * fix(android): Remove stale NDK crash IPC files Name the shared-memory file after the app pid and delete leftovers whose process no longer runs when the crash service starts. A setup that fails before the daemon attaches would otherwise leave the file behind, while other processes of a multi-process app keep theirs. * fix(android): Fall back to the 1-argument NDK init With a context, NdkIntegration only looked up `SentryNdk.init(Context, SentryAndroidOptions)`. An older sentry-android-ndk without it disabled NDK. Fall back to `SentryNdk.init(SentryAndroidOptions)` and log a warning. * ref(android): Stop passing the tombstone flag to NdkOptions sentry-native-ndk-outproc no longer reads it, because it always sends native crash envelopes without a minidump. The crash service still gets the tombstone flag through its configure call. * fix(android): Skip SDK init in the NDK crash service process The crash service runs in its own `.sentry_ndk_crash` process, which runs the app's `Application.onCreate`. Apps that call `SentryAndroid.init` there started a second SDK on every launch, with the tombstone, ANR and outbox senders working on the same cache directory as the app process. Return early from `SentryAndroid.init` in that process. * ref(android): Remove the NDK crash service process check SentryAndroid.init now returns early in the `.sentry_ndk_crash` process, so SentryNdk.init is no longer called there. * fix(android): Keep a newer NDK tombstone marker Crash service workers for processes that crash close together can finish out of order. A worker that wrote an older tombstone timestamp let `TombstoneIntegration` report the newer crash again on the next launch. Write the marker only when it is newer than the current one, and serialize the workers. * ci: Stop the sentry-native Gradle daemon after publishing The publish step left its 4 GB Gradle daemon running alongside the 8 GB daemon used by `make preMerge`. The job was killed about 12 minutes into the tests, most likely because the runner ran out of memory. * fix(android): Bind the NDK crash service as important Without `BIND_IMPORTANT`, a foreground app raises its bound crash service process only to the visible oom adj (100), so lmkd would kill the service before the app under memory pressure. The flag gives the service the app's own adj (0) while the app is on top, without lowering the app's priority the way `BIND_ABOVE_CLIENT` would. * Apply batched suggestions from code review Co-authored-by: Roman Zavarnitsyn * chore(android): Update the outproc API dump The outproc module shares NdkScopeObserver with the inproc module, which gained setEnvironment on main (#5772). * fix(android): Reattach the NDK crash daemon after a service restart When the crash service process died while the app was bound, Android restarted it and called `onServiceConnected` again, but the connection had already closed the descriptors it configured with, so the app ran without a crash daemon. Configure the restarted service with new pipes and the app's shared memory file, then reattach the native crash IPC. Bind again when the binding dies, and log a lost connection at ERROR. * ref(android): Build the NDK outproc package on top of sentry-android-ndk sentry-android-ndk-outproc compiled sentry-android-ndk's sources through extra source folders, shared its namespace and borrowed its ProGuard rules, so the same files belonged to both modules, and the deprecated `BaseExtension` wired it up. Depend on sentry-android-ndk instead, without its `sentry-native-ndk`, and keep only the crash service and the `SentryNdkOutproc` entry point in the `io.sentry.android.ndk.outproc` namespace. `NdkIntegration` now loads that entry point first and falls back to `SentryNdk`. * fix(android): Write the NDK tombstone marker before the send The native side keeps the envelope for the next launch until it is sent, so the crash is delivered whatever the send result. Write the marker before the send, so that a send that a frozen service finishes late no longer races TombstoneIntegration on the next launch. * fix(android): Close rejected NDK crash service fds `configureDaemon` left the file descriptors of a binder transaction open until garbage collection when it rejected the configuration. Close them before returning. * fix(android): Time the NDK tombstone poll with a monotonic clock The crash service polled for a matching tombstone until a wall clock deadline, so a clock step backward delayed the crash send by the size of the step. Use `SystemClock.uptimeMillis()`, which also drives `Thread.sleep()`. * fix(android): Narrow the NDK outproc library load catch The library loader thread swallowed every `Throwable`, including fatal errors. Catch only the `UnsatisfiedLinkError` of a missing or broken library, which `init()` reports later. `ExceptionUtils.rethrowIfFatal` does not fit, because it rethrows `LinkageError` and would turn a missing library into an app crash. * fix(android): Load the NDK outproc libraries before binding the service A missing or broken native library surfaced only in `initCrashDaemon`, after the crash service was bound and the IPC fds were detached. The `UnsatisfiedLinkError` left the service bound with `BIND_IMPORTANT` and the fds open for the app's lifetime. Load the libraries first, so the failure leaves nothing behind. * fix(android): Write the NDK tombstone marker when the merge fails When the crash service matched the app's native crash exit but could not merge its tombstone, because it stayed unavailable until the deadline or the merge threw, it sent the native event without writing the marker. On the next launch, `TombstoneIntegration` then reported the same crash again as a standalone tombstone event. Write the marker for a matched tombstone, merged or not. * docs(android): Remove the Gradle plugin from the NDK outproc README The `ndkBackend` option of the Gradle plugin is parked for now, so the outproc package is selected through its dependency only. * fix(android): Hand the NDK crash memfd to the crash service The NDK now backs the crash IPC with a memfd instead of a file, because the sparse file could raise `SIGBUS` on a full disk. Create the memfd before configuring the service and send it over Binder, which reattaching already does. This removes the file path from the protocol, and the cleanup of stale files. * docs(changelog): Move the outproc entry back to Unreleased The merge of `origin/main` placed it under `8.63.0`, which was released without out-of-process crash reporting. * build(deps): Bump sentry-native-ndk-outproc to 1.0.0-beta.1 sentry-native now publishes `sentry-native-ndk-outproc` to Maven Central, so CI no longer builds it from the sentry-native branch into Maven Local. * meta(android): Register the NDK outproc module for release Craft's `registry` target fails the release when a published module has no entry. Also list the module in the README packages table and the Android issue template. * ref(android): Pass the thread id as the NDK crash daemon's appTid `appTid` received `System.nanoTime()`, but the daemon expects the parent thread id. On Android it only names the shared memory file that the daemon unlinks, and none exists because the memory is a memfd. * ref(android): Time the NDK tombstone poll with a Deadline New code reads clocks through `io.sentry.time` instead of `SystemClock`. The poll deadline now comes from the options' monotonic ticker, which also counts time the device spends suspended. * ref(android): Document the NDK crash service's broad catches The exception rules in `AGENTS.md` allow a broad catch only at a boundary, with a comment on why and what happens on failure. The two `Exception` catches also call `ExceptionUtils.rethrowIfFatal`, which restores the interrupt flag of a swallowed `InterruptedException`. * fix(android): Unbind the NDK crash service on any native init failure `SentryNdkOutproc.init` only unbound the crash service when native init threw `IllegalStateException`. Any other throwable, such as an `UnsatisfiedLinkError`, left the service bound with `BIND_IMPORTANT`, and the disabled NDK integration never closed it. * docs(changelog): Explain how to enable Android outproc crash reporting --------- Co-authored-by: Roman Zavarnitsyn --- .craft.yml | 5 + .github/ISSUE_TEMPLATE/bug_report_android.yml | 1 + CHANGELOG.md | 3 + README.md | 1 + .../main/kotlin/io/sentry/gradle/AarTypes.kt | 1 + gradle/libs.versions.toml | 1 + scripts/update-sentry-native-ndk.sh | 2 +- .../api/sentry-android-core.api | 2 + .../core/AndroidOptionsInitializer.java | 9 +- .../sentry/android/core/NdkIntegration.java | 32 +- .../io/sentry/android/core/SentryAndroid.java | 20 + .../android/core/TombstoneIntegration.java | 2 +- .../core/AndroidOptionsInitializerTest.kt | 16 + .../sentry/android/core/NdkIntegrationTest.kt | 17 + .../sentry/android/core/SentryAndroidTest.kt | 13 + sentry-android-ndk-outproc/README.md | 21 + .../api/sentry-android-ndk-outproc.api | 19 + sentry-android-ndk-outproc/build.gradle.kts | 88 ++ sentry-android-ndk-outproc/proguard-rules.pro | 6 + .../src/main/AndroidManifest.xml | 10 + .../ndk/outproc/SentryNdkCrashService.java | 813 ++++++++++++++++++ .../android/ndk/outproc/SentryNdkOutproc.java | 178 ++++ .../android/ndk/outproc/NativeBackendTest.kt | 91 ++ .../ndk/outproc/SentryNdkCrashServiceTest.kt | 514 +++++++++++ .../SentryShadowParcelFileDescriptor.kt | 22 + sentry-android-ndk/api/sentry-android-ndk.api | 1 + .../java/io/sentry/android/ndk/SentryNdk.java | 12 + .../sentry/android/ndk/SentryNdkUtilTest.kt | 3 +- settings.gradle.kts | 1 + 29 files changed, 1895 insertions(+), 9 deletions(-) create mode 100644 sentry-android-ndk-outproc/README.md create mode 100644 sentry-android-ndk-outproc/api/sentry-android-ndk-outproc.api create mode 100644 sentry-android-ndk-outproc/build.gradle.kts create mode 100644 sentry-android-ndk-outproc/proguard-rules.pro create mode 100644 sentry-android-ndk-outproc/src/main/AndroidManifest.xml create mode 100644 sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java create mode 100644 sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkOutproc.java create mode 100644 sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt create mode 100644 sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt create mode 100644 sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryShadowParcelFileDescriptor.kt diff --git a/.craft.yml b/.craft.yml index d725b0e93db..4ab5c35c4eb 100644 --- a/.craft.yml +++ b/.craft.yml @@ -124,6 +124,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/.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/CHANGELOG.md b/CHANGELOG.md index d3243f9991b..6f4cde134bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,9 @@ - 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. ### Behavioral Changes diff --git a/README.md b/README.md index f94eb9a9ae7..a5d83a8dadf 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) | 21 | | 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) | 21 | | 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) | 21 | +| 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) | 21 | | 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) | 21 | | 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) | 21 | | 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) | 21 | 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/gradle/libs.versions.toml b/gradle/libs.versions.toml index 648f6a4bccf..590670955bf 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -194,6 +194,7 @@ reactor-core = { module = "io.projectreactor:reactor-core", version = "3.5.3" } retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" } retrofit-gson = { module = "com.squareup.retrofit2:converter-gson", version.ref = "retrofit" } sentry-native-ndk = { module = "io.sentry:sentry-native-ndk", version = "0.17.6" } +sentry-native-ndk-outproc = { module = "io.sentry:sentry-native-ndk-outproc", version = "1.0.0-beta.1" } servlet-api = { module = "javax.servlet:javax.servlet-api", version = "3.1.0" } servlet-jakarta-api = { module = "jakarta.servlet:jakarta.servlet-api", version = "6.1.0" } slf4j-api = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } 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 4c479759f5a..4c972c1f3d3 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -376,6 +376,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 @@ -680,6 +681,7 @@ public final class io/sentry/android/core/TombstoneIntegration$TombstonePolicy : 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 } 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 73f04af149c..52a54b339dc 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; @@ -438,8 +439,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)); 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/SentryAndroid.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java index bdfb1646a00..7439de759d7 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 @@ -3,6 +3,7 @@ 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,6 +49,9 @@ public final class SentryAndroid { private static final String FRAGMENT_CLASS_NAME = "androidx.fragment.app.FragmentManager$FragmentLifecycleCallbacks"; + // 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"); @@ -280,4 +290,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/TombstoneIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java index 03e7c36b565..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 @@ -290,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/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt index 7c7acf8ef3b..2a9d8cb905b 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 @@ -52,6 +52,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 @@ -125,6 +126,7 @@ class AndroidOptionsInitializerTest { fun initSutWithClassLoader( classesToLoad: List = emptyList(), + loadedClasses: Map> = emptyMap(), isFragmentAvailable: Boolean = false, isTimberAvailable: Boolean = false, isReplayAvailable: Boolean = false, @@ -138,6 +140,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) + } val activityFramesTracker = ActivityFramesTracker(loadClass, sentryOptions) AndroidOptionsInitializer.loadDefaultAndMetadataOptions( @@ -640,6 +645,17 @@ class AndroidOptionsInitializerTest { 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()) 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/SentryAndroidTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt index 725a5a61122..b5559582610 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 @@ -84,6 +84,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 @RunWith(AndroidJUnit4::class) @Config(sdk = [Build.VERSION_CODES.N], shadows = [SentryShadowProcess::class]) @@ -573,6 +574,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-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..8e3cce43343 --- /dev/null +++ b/sentry-android-ndk-outproc/build.gradle.kts @@ -0,0 +1,88 @@ +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") +} + +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..96a68c1960f --- /dev/null +++ b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt @@ -0,0 +1,91 @@ +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..b8bf6f31e29 --- /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/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/SentryNdkUtilTest.kt b/sentry-android-ndk/src/test/java/io/sentry/android/ndk/SentryNdkUtilTest.kt index a3f5e9a8f93..943e4fb6df7 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,8 +12,7 @@ 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/settings.gradle.kts b/settings.gradle.kts index 852765c03d8..18340a6c241 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", From 94f84caa55a812a11b456ffaee3bbdb824e0677e Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Wed, 11 Nov 2026 15:14:38 +0100 Subject: [PATCH 20/51] test(android): Use fewer Robolectric SDK levels in core and replay (#6544) * collection: Robolectric CI speed-up * test(android): Use fewer Robolectric SDK levels in core and replay Robolectric starts a new sandbox for each SDK level a test JVM uses, and downloads one android-all jar per level. Move pinned levels to the nearest shared level that takes the same code branch: 23/25 -> 24, 26 -> 30, 31/34 -> 33. Level 28 stays because ReplaySmokeTest and AndroidConnectionStatusProviderTest behave differently at 30. Core and replay now use 6 levels instead of 11. Locally, core Robolectric tests go from about 82s to 71s. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../core/ActivityLifecycleIntegrationTest.kt | 4 ++-- .../android/core/AndroidOptionsInitializerTest.kt | 14 +++++++------- .../ApplicationExitInfoCrossIntegrationTest.kt | 2 +- .../android/core/ScreenshotEventProcessorTest.kt | 2 +- .../io/sentry/android/core/SentryAndroidTest.kt | 4 ++-- .../android/core/SessionTrackingIntegrationTest.kt | 2 +- .../android/core/TombstoneIntegrationTest.kt | 2 +- ...droidConnectionStatusProviderConcurrencyTest.kt | 2 +- .../util/AndroidConnectionStatusProviderTest.kt | 2 +- .../util/CellularNetworkTechnologyProviderTest.kt | 2 +- .../core/internal/util/ScreenshotUtilTest.kt | 2 +- .../io/sentry/android/replay/ReplayCacheTest.kt | 2 +- .../sentry/android/replay/ReplayIntegrationTest.kt | 2 +- .../replay/ReplayIntegrationWithRecorderTest.kt | 2 +- 14 files changed, 22 insertions(+), 22 deletions(-) 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 27f339aff31..1a88c1bec6d 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 @@ -704,8 +704,8 @@ class ActivityLifecycleIntegrationTest { } @Test - @Config(sdk = [Build.VERSION_CODES.M]) - fun `onHeadlessAppStart creates standalone App Start transaction on API 23`() { + @Config(sdk = [Build.VERSION_CODES.N]) + fun `onHeadlessAppStart creates standalone App Start transaction on API 24`() { val sut = fixture.getSut { it.tracesSampleRate = 1.0 it.isEnableStandaloneAppStartTracing = true 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 2a9d8cb905b..5b1c25d82ef 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 @@ -375,7 +375,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 }) @@ -383,7 +383,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" }) @@ -391,7 +391,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 }) @@ -399,7 +399,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() @@ -442,7 +442,7 @@ class AndroidOptionsInitializerTest { ) } - @Config(sdk = [34]) + @Config(sdk = [33]) @Test fun `init below API 35 does not report PerfettoContinuousProfiling integration`() { SentryIntegrationPackageStorage.getInstance().clearStorage() @@ -455,14 +455,14 @@ class AndroidOptionsInitializerTest { ) } - @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 }) 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..cac76c024af 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() 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 0abb232b807..b27df5f6bf1 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 @@ -202,7 +202,7 @@ class ScreenshotEventProcessorTest { } @Test - @Config(sdk = [23]) + @Config(sdk = [24]) fun `when screenshot event processor is called from background thread it executes on main thread`() { val sut = fixture.getSut(true) whenever(fixture.threadChecker.isMainThread).thenReturn(false) 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 b5559582610..36a23bf3688 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 @@ -350,7 +350,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() @@ -359,7 +359,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() 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 6c8eaa4d851..775726423bc 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 @@ -36,7 +36,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 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..ca4c51319aa 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 = 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 index d201d48d111..ed37286026f 100644 --- 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 @@ -61,7 +61,7 @@ import org.robolectric.annotation.Config * that must not wait for them run on a separate caller thread with a bounded wait. */ @RunWith(AndroidJUnit4::class) -@Config(sdk = [Build.VERSION_CODES.S]) +@Config(sdk = [Build.VERSION_CODES.TIRAMISU]) class AndroidConnectionStatusProviderConcurrencyTest { @AfterTest 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 9c209006cb6..b0fa556deae 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 @@ -258,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. 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 4bf1d7de427..64d2b3dc281 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() 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-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..8e08b936bd5 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() 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..1dad10238f5 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() 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() From 16e51eed841bee5cec735e8562379e9e1e83ddd4 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 11 Nov 2026 15:42:27 +0100 Subject: [PATCH 21/51] chore(docs): Remove OkHttp version bump from changelog and add known issue for #6537 (#6561) --- CHANGELOG.md | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f4cde134bb..bdb17f37298 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,7 +35,7 @@ ### Fixes - 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 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)) +- 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)) @@ -45,13 +45,6 @@ - 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)) -### Dependencies - -- 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) - ## 8.63.0 ### Features @@ -94,6 +87,10 @@ - Measure ANR detection and ANR profiling durations on the internal `MonotonicTicker` ([#6041](https://github.com/getsentry/sentry-java/pull/6041)) +### 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 by [#6537](https://github.com/getsentry/sentry-java/pull/6537). + ## 8.62.0 ### Improvements @@ -107,6 +104,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 by [#6537](https://github.com/getsentry/sentry-java/pull/6537). + ## 8.61.1 ### Fixes @@ -134,6 +135,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 by [#6537](https://github.com/getsentry/sentry-java/pull/6537). + ## 8.61.0 ### Fixes @@ -164,6 +169,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 by [#6537](https://github.com/getsentry/sentry-java/pull/6537). + ## 8.60.0 ### Features @@ -179,6 +188,10 @@ - [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 by [#6537](https://github.com/getsentry/sentry-java/pull/6537). + ## 8.59.0 ### Breaking Changes From cc83d6bbb3d5a11518ec175465518fd657547a03 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 11 Nov 2026 15:45:40 +0100 Subject: [PATCH 22/51] build(android): Run Error Prone and NullAway on the Android modules (#6493) * build(android): Run Error Prone and NullAway on the Android modules net.ltgt.errorprone dropped Android support in 3.0.0, which we have used since 6.7. Since then it only enables Error Prone and adds it to the processor path for Gradle's JVM source sets. On sentry-android-core and sentry-uitest-android the errorprone dependencies and the NullAway ERROR setting had no effect, and the Java compile tasks ran plain javac. Use the AGP variant API to add the errorprone configuration to each variant's annotation processor configuration and enable Error Prone on its JavaCompile task. Both APIs exist in AGP 9.0.0, the oldest version in the AGP matrix. Pass -XDandroidCompatible=true so Error Prone treats these modules as Android code: it skips checks that don't apply there, such as DefaultCharset, and runs its Android checks. sentry-uitest-android has no hand-written Java, so exclude the view binding classes AGP generates, which trip LabelledBreakTarget. Co-Authored-By: Claude Opus 5.5 * fix(android): Resolve NullAway findings in AndroidConnectionStatusProvider NullAway treats AtomicReference.get() as nullable, so the snapshot reads added in #6537 fail once NullAway runs on sentry-android-core. The snapshot is never set to null, so read it through one accessor that suppresses the finding. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- sentry-android-core/build.gradle.kts | 17 ++++++++++---- .../util/AndroidConnectionStatusProvider.java | 22 ++++++++++++------- .../sentry-uitest-android/build.gradle.kts | 21 +++++++++++++----- 3 files changed, 43 insertions(+), 17 deletions(-) diff --git a/sentry-android-core/build.gradle.kts b/sentry-android-core/build.gradle.kts index c261c56f785..2c175f4c387 100644 --- a/sentry-android-core/build.gradle.kts +++ b/sentry-android-core/build.gradle.kts @@ -74,10 +74,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") + } } } 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 256cf88e7b0..df8a3b976dc 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 @@ -324,7 +324,7 @@ private void ensureNetworkCallbackRegistered() { public void onAvailable(final @NotNull Network network) { @NotNull ConnectionSnapshot current; do { - current = snapshot.get(); + current = currentSnapshot(); } while (!snapshot.compareAndSet(current, current.withNetwork(network))); // Only forward the call on first registration + when the connection is @@ -348,7 +348,7 @@ public void onUnavailable() { @Override public void onLost(final @NotNull Network network) { - if (!network.equals(snapshot.get().network)) { + if (!network.equals(currentSnapshot().network)) { return; } clearCacheAndNotifyObservers(); @@ -376,7 +376,7 @@ private void clearCacheAndNotifyObservers() { @Override public void onCapabilitiesChanged( @NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) { - if (!network.equals(snapshot.get().network)) { + if (!network.equals(currentSnapshot().network)) { return; } updateCacheAndNotifyObservers(networkCapabilities); @@ -397,7 +397,7 @@ private void updateCacheAndNotifyObservers( @NotNull ConnectionSnapshot current; @NotNull ConnectionSnapshot updated; do { - current = snapshot.get(); + current = currentSnapshot(); if (!isSignificantChange(current.capabilities, networkCapabilities)) { return; } @@ -482,9 +482,15 @@ private boolean hasSignificantTransportChanges( } } + // NullAway treats AtomicReference.get() as nullable, but the snapshot is never set to null. + @SuppressWarnings("NullAway") + private @NotNull ConnectionSnapshot currentSnapshot() { + return snapshot.get(); + } + /** The current snapshot, refreshed first if it's stale. */ private @NotNull ConnectionSnapshot freshSnapshot() { - final @NotNull ConnectionSnapshot current = snapshot.get(); + final @NotNull ConnectionSnapshot current = currentSnapshot(); return current.isFresh() ? current : refresh(current); } @@ -510,7 +516,7 @@ private boolean hasSignificantTransportChanges( if (snapshot.compareAndSet(current, refreshed)) { break; } - current = snapshot.get(); + current = currentSnapshot(); if (current.isFresh()) { return current; } @@ -651,7 +657,7 @@ public void onForeground() { // proactively update cache and notify observers on foreground to ensure connectivity // state is not stale - final @NotNull ConnectionStatus status = statusOf(refresh(snapshot.get())); + 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 @@ -699,7 +705,7 @@ public void onBackground() { @TestOnly @Nullable public NetworkCapabilities getCachedNetworkCapabilities() { - return snapshot.get().capabilities; + return currentSnapshot().capabilities; } /** 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 784bd463c55..557a5fab63a 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts +++ b/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts @@ -135,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/.*") + } } } From 683908daaa63add97ca9a1710ab4a6898ada1c2b Mon Sep 17 00:00:00 2001 From: 0xadam-brown <281682121+0xadam-brown@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:46:02 +0000 Subject: [PATCH 23/51] release: 8.64.0 --- CHANGELOG.md | 2 +- gradle.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bdb17f37298..2bf5027ddd3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ > - Java 8 support will be dropped. SDK 9.0.0 requires Java 11+. See [#6469](https://github.com/getsentry/sentry-java/issues/6469). > - The Android `minSdk` will be raised from 21 to 24. See [#5508](https://github.com/getsentry/sentry-java/issues/5508). -## Unreleased +## 8.64.0 ### Breaking Changes 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 From 393de0d3aa2d685fca4f553e363b94cd9eb99717 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 11 Nov 2026 16:10:30 +0100 Subject: [PATCH 24/51] build(android): Download Robolectric android-all jars with Gradle (#6553) Robolectric fetched ~0.95 GB of android-all jars from Maven Central while tests ran, and CI doesn't cache ~/.m2, so every Build run downloaded them again. A new io.sentry.robolectric build-logic plugin resolves them with Gradle before the tests start, so setup-gradle restores them from cache, and points Robolectric at them through robolectric-deps.properties instead of copying them into robolectric.dependency.dir. See https://robolectric.org/blog/2023/11/11/improving-android-all-downloading/ Co-authored-by: Claude Opus 5.5 --- build-logic/build.gradle.kts | 4 + .../sentry/gradle/SentryRobolectricPlugin.kt | 115 ++++++++++++++++++ gradle/libs.versions.toml | 1 + sentry-android-core/build.gradle.kts | 1 + sentry-android-distribution/build.gradle.kts | 1 + sentry-android-navigation/build.gradle.kts | 1 + sentry-android-navigation3/build.gradle.kts | 1 + sentry-android-ndk-outproc/build.gradle.kts | 1 + sentry-android-replay/build.gradle.kts | 1 + sentry-compose/build.gradle.kts | 1 + 10 files changed, 127 insertions(+) create mode 100644 build-logic/src/main/kotlin/io/sentry/gradle/SentryRobolectricPlugin.kt diff --git a/build-logic/build.gradle.kts b/build-logic/build.gradle.kts index 2c48083cdce..db40bf74435 100644 --- a/build-logic/build.gradle.kts +++ b/build-logic/build.gradle.kts @@ -42,6 +42,10 @@ 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" 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/gradle/libs.versions.toml b/gradle/libs.versions.toml index 590670955bf..d6a55ba3d56 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -306,6 +306,7 @@ okhttp-mockwebserver4 = { module = "com.squareup.okhttp3:mockwebserver", version 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/sentry-android-core/build.gradle.kts b/sentry-android-core/build.gradle.kts index 2c175f4c387..64ea145514b 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 { diff --git a/sentry-android-distribution/build.gradle.kts b/sentry-android-distribution/build.gradle.kts index d4bedf0a02c..c6e4bf44cbb 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 { diff --git a/sentry-android-navigation/build.gradle.kts b/sentry-android-navigation/build.gradle.kts index af9aef5166c..9c23e6111e1 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 { diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index ce2ab209af8..6d4f70fc9f1 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 { diff --git a/sentry-android-ndk-outproc/build.gradle.kts b/sentry-android-ndk-outproc/build.gradle.kts index 8e3cce43343..bb8fd5151a4 100644 --- a/sentry-android-ndk-outproc/build.gradle.kts +++ b/sentry-android-ndk-outproc/build.gradle.kts @@ -8,6 +8,7 @@ plugins { id("io.sentry.jdk-target") id("io.sentry.publish") id("io.sentry.api-validation") + id("io.sentry.robolectric") } android { diff --git a/sentry-android-replay/build.gradle.kts b/sentry-android-replay/build.gradle.kts index 8d17ff27f1e..034268031b4 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 { diff --git a/sentry-compose/build.gradle.kts b/sentry-compose/build.gradle.kts index 6bcd20e2a36..69d4db93866 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 { From 72c891bbc6b211a1c8f636236c9e3a61d8e09bdf Mon Sep 17 00:00:00 2001 From: Markus Hintersteiner Date: Thu, 12 Nov 2026 09:46:26 +0100 Subject: [PATCH 25/51] feat(profiling): Store the thread state in ANR stack samples (#6587) * ref(android): Store the thread state in ANR stack samples * ref(android): Mark a null ANR sample state explicitly and document the format * ref(android): Remove narrating comments from AnrStackTrace --- .../api/sentry-android-core.api | 2 + .../android/core/anr/AnrStackTrace.java | 48 +++++++++- .../android/core/anr/AnrStackTraceTest.kt | 88 +++++++++++++++++++ 3 files changed, 135 insertions(+), 3 deletions(-) diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 4c972c1f3d3..712f981ecd2 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -759,8 +759,10 @@ public final class io/sentry/android/core/anr/AnrProfilingIntegration : io/sentr 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; 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/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()))) + } } From cb5a46269b12ce8da3c9b8d3f9b56860419d0653 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 12 Nov 2026 09:56:54 +0100 Subject: [PATCH 26/51] chore(docs): Add version for fix under Known Issues entries in changelog (#6569) --- CHANGELOG.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bf5027ddd3..31ff06f1e99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,7 +89,7 @@ ### 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 by [#6537](https://github.com/getsentry/sentry-java/pull/6537). +- 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 @@ -106,7 +106,7 @@ ### 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 by [#6537](https://github.com/getsentry/sentry-java/pull/6537). +- 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 @@ -137,7 +137,7 @@ ### 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 by [#6537](https://github.com/getsentry/sentry-java/pull/6537). +- 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 @@ -171,7 +171,7 @@ ### 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 by [#6537](https://github.com/getsentry/sentry-java/pull/6537). +- 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 @@ -190,7 +190,7 @@ ### 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 by [#6537](https://github.com/getsentry/sentry-java/pull/6537). +- 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 From cef4eab044cabdf952f87dc3fc696db563f32f7c Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Thu, 12 Nov 2026 12:56:33 +0100 Subject: [PATCH 27/51] fix(android): Measure debounce windows on the monotonic ticker (JAVA-729) (#6590) * fix(android): Measure debounce windows on the monotonic ticker (JAVA-729) Debouncer read AndroidCurrentDateProvider, which is SystemClock.uptimeMillis() and stops in deep sleep. A window that expired while the device slept still looked open, so the first low-memory or battery breadcrumb after a long Doze could be dropped. Debouncer now measures its window with a Deadline on options.getMonotonicTicker(), which is CLOCK_BOOTTIME on Android. The screenshot, view hierarchy, system events and app components debouncers all use it. AndroidEnvelopeCache still uses AndroidCurrentDateProvider: it compares against TimeSpan's uptime start, so it can't move on its own. Refs JAVA-729 Co-Authored-By: Claude Opus 5.5 * changelog --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 6 +++ .../AppComponentsBreadcrumbsIntegration.java | 11 +++--- .../core/ScreenshotEventProcessor.java | 8 +--- .../SystemEventsBreadcrumbsIntegration.java | 8 ++-- .../core/ViewHierarchyEventProcessor.java | 8 +--- .../android/core/internal/util/Debouncer.java | 31 ++++++++------- .../core/internal/util/DebouncerTest.kt | 39 +++++++++---------- 7 files changed, 52 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31ff06f1e99..1e05874449d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ > - Java 8 support will be dropped. SDK 9.0.0 requires Java 11+. See [#6469](https://github.com/getsentry/sentry-java/issues/6469). > - The Android `minSdk` will be raised from 21 to 24. See [#5508](https://github.com/getsentry/sentry-java/issues/5508). +## Unreleased + +### Fixes + +- 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)) + ## 8.64.0 ### Breaking Changes 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 6dfcb888f3f..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; } 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 8b51c512c87..849f1099484 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/SystemEventsBreadcrumbsIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java index ae57b75ab4a..82bd4ce9f72 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; @@ -300,15 +299,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/ViewHierarchyEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java index fb56d1778fb..8fad115eed6 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"); 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 1715993f4fe..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,29 +1,33 @@ 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 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); } /** @@ -31,10 +35,9 @@ public Debouncer( * 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/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()) From bcc7c3dbf6a0fb9cba2a2e1ce6fb0979134f752b Mon Sep 17 00:00:00 2001 From: Markus Hintersteiner Date: Thu, 12 Nov 2026 14:10:48 +0100 Subject: [PATCH 28/51] ref(android): Remove unused BreadcrumbFactory (#6598) --- .../core/internal/util/BreadcrumbFactory.java | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 sentry-android-core/src/main/java/io/sentry/android/core/internal/util/BreadcrumbFactory.java 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 d0ae75f7f8a..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 final 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; - } -} From b98d31ab61a9aca15f67aab130fa5a9f45755152 Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Thu, 12 Nov 2026 22:25:49 +0100 Subject: [PATCH 29/51] perf(core): Avoid allocations in log calls when debug is off (#6600) * perf(core): Avoid allocations in log calls when debug is off Every SDK log call allocated a varargs array at the call site, also when debug is off. ILogger now has fixed-arity default overloads for zero, one and two arguments, which DiagnosticLogger and NoOpLogger override. Recompiled call sites use them and do not allocate when logging is disabled. Hot-path log calls in DefaultCompositePerformanceCollector and SentryGestureListener also built their messages eagerly with string concatenation or toString(). They now pass format arguments, so the message is built only when logging is enabled. Co-Authored-By: Claude Opus 5.5 * changelog Co-Authored-By: Claude Opus 5.5 * changelog: Narrow the allocation claim Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 4 ++ .../gestures/SentryGestureListener.java | 13 +++---- .../ApplicationExitIntegrationTestBase.kt | 8 +--- sentry/api/sentry.api | 9 +++++ .../DefaultCompositePerformanceCollector.java | 4 +- .../main/java/io/sentry/DiagnosticLogger.java | 26 +++++++++++++ sentry/src/main/java/io/sentry/ILogger.java | 39 +++++++++++++++++++ .../src/main/java/io/sentry/NoOpLogger.java | 13 +++++++ .../test/java/io/sentry/OutboxSenderTest.kt | 17 ++++++-- .../io/sentry/PreviousSessionFinalizerTest.kt | 2 - 10 files changed, 115 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e05874449d..604b95a9e8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ ## Unreleased +### Performance + +- Most SDK log calls no longer allocate when `debug` is off ([#6600](https://github.com/getsentry/sentry-java/pull/6600)) + ### Fixes - 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)) 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 12ca130be9e..bb741d0cb2a 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) { @@ -351,7 +350,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; } @@ -359,7 +358,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; } @@ -367,7 +366,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/test/java/io/sentry/android/core/ApplicationExitIntegrationTestBase.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitIntegrationTestBase.kt index 7db354ea64c..3de3e054630 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()) } diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index dfce80a93d8..240a52a43d0 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 @@ -944,6 +947,9 @@ public abstract interface class io/sentry/IHub : io/sentry/IScopes { 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 @@ -1804,6 +1810,9 @@ public final class io/sentry/NoOpHub : io/sentry/IHub { 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 diff --git a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java index 2b5a386300b..89373516e2c 100644 --- a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java +++ b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java @@ -168,7 +168,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); @@ -180,7 +180,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/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/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/test/java/io/sentry/OutboxSenderTest.kt b/sentry/src/test/java/io/sentry/OutboxSenderTest.kt index 703f0823c00..cf4c7d30830 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 @@ -310,7 +309,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()) } @@ -328,7 +333,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..4c8510facca 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 @@ -281,7 +280,6 @@ class PreviousSessionFinalizerTest { "Timed out waiting to flush previous session to its own file in session finalizer." ) }, - anyVararg(), ) verify(fixture.scopes, never()).captureEnvelope(any()) } From 13ec6c78fe61a5e2a46c0d06475b764ca42988d0 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Fri, 13 Nov 2026 09:02:45 +0100 Subject: [PATCH 30/51] fix(android): Don't swallow interrupts while flushing a startup crash (#6568) * fix(android): Don't swallow interrupts while flushing a startup crash After a startup crash, SendCachedEnvelopeIntegration blocks the thread that calls Sentry.init until the cached envelopes are sent. If that thread was interrupted, future.get() cleared the interrupt and the trailing catch (Throwable) swallowed it, so the caller never saw it. It also logged that cached events will not be sent, although the task keeps sending them. Catch InterruptedException next to the timeout, restore the interrupt and continue in the background. Co-Authored-By: Claude Opus 5.5 * changelog --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../core/SendCachedEnvelopeIntegration.java | 7 ++++++ .../core/SendCachedEnvelopeIntegrationTest.kt | 22 +++++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 604b95a9e8f..6a187354b76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ ### Fixes +- 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)) 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..05352be394c 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 @@ -157,6 +157,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/test/java/io/sentry/android/core/SendCachedEnvelopeIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SendCachedEnvelopeIntegrationTest.kt index df9ce60883e..32b38764626 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 @@ -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 = From 3b6fa83fe5752710bd22cba02ff5c59a636b4f5f Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Fri, 13 Nov 2026 10:49:15 +0100 Subject: [PATCH 31/51] feat(replay): Add pauseTouchTracking and resumeTouchTracking (#6546) Apps can stop recording touches on sensitive screens, such as a custom PIN pad, while the masked screen recording continues. Masking hides the content, but recorded touch positions could reveal the input. The flag is independent of pause()/resume() and is cleared only by resumeTouchTracking(), also across new replays. It is set directly instead of being queued on the main thread, so it applies to touch events that are already pending. Also mark debugMaskingEnabled as volatile, it is written and read on different threads. Fixes JAVA-658 Fixes #5787 Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 4 + .../api/sentry-android-replay.api | 2 + .../android/replay/ReplayIntegration.kt | 17 +++- .../android/replay/ReplayIntegrationTest.kt | 87 +++++++++++++++++++ sentry/api/sentry.api | 4 + .../src/main/java/io/sentry/IReplayApi.java | 17 ++++ .../java/io/sentry/NoOpReplayController.java | 6 ++ 7 files changed, 135 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a187354b76..76789a90411 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ ## Unreleased +### Features + +- 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)) 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/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 4d6614a7832..bebaf95d396 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 @@ -397,6 +402,14 @@ public class ReplayIntegration( } } + override fun pauseTouchTracking() { + isTouchTrackingPaused = true + } + + override fun resumeTouchTracking() { + isTouchTrackingPaused = false + } + override fun enableDebugMaskingOverlay() { debugMaskingEnabled = true } @@ -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) 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 1dad10238f5..49ec8565c1b 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 @@ -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/api/sentry.api b/sentry/api/sentry.api index 240a52a43d0..17ca4e62279 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -988,7 +988,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 @@ -1842,9 +1844,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/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/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() {} From 2e298a3f1e0822576d37d78830a38ece1449a201 Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Fri, 13 Nov 2026 10:51:36 +0100 Subject: [PATCH 32/51] test(okhttp): Wait until the reader is blocked before closing the body (#6604) The concurrent close test signaled right after the reader got the first chunk, before it entered the next read(). When close() landed in that gap, the reader's next read() threw Okio's "closed" IllegalStateException, the thread died, and the test timed out waiting for it. ParkingSource now signals right before it blocks, so close() always lands while the reader is inside read(). Co-authored-by: Claude Fable 5.1 --- .../java/io/sentry/okhttp/CapturedResponseBodyTest.kt | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) 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( From f69512edc2c60243e6fcee050f49b376056e47eb Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 13 Nov 2026 11:35:25 +0100 Subject: [PATCH 33/51] fix(android): Part 3 of Nav3 support for multi-Activity and multi-Fragment apps (JAVA-785, JAVA-823) (#6480) This commit constitutes part 3 of our Nav3 support for multi-Activity and multi-Fragment apps. In part 1 (https://github.com/getsentry/sentry-java/pull/6301) we provided the basic mechanism for coordinating multiple SentryNavEffects; and in part 2 (https://github.com/getsentry/sentry-java/pull/6398) we adapted our approach to the quirks of ViewPager2 and other oddball Fragment lifecycles. Both of those commits assumed that any Activities or Fragments that had a SentryNavEffect would only launch other Activities or Fragments that also had SentryNavEffects. This commit handles three remaining (and important) corner cases: 1. Ensuring spans don't get lost when the user returns to an Activity or Fragment they already visited. (We now start a new nav transaction when the user returns if the previous transaction finished in the meantime.) 2. Ensuring Activities or Fragments with SentryNavEffects play nicely with Activities or Fragments without them. (We no longer keep stale nav data in the shared IScope.) 3. Ensuring Activities' ui.load transactions interoperate well with Nav3 transactions. (Nav3 transactions now consistently defer to ui.load transactions, like we do for Nav2.) See the PR description of https://github.com/getsentry/sentry-java/pull/6480 for more details. --- CHANGELOG.md | 6 + sentry-android-navigation3/build.gradle.kts | 7 + .../compose/navigation3/BackStackObserver.kt | 143 +-- .../CoordinatedBackStackObserver.kt | 31 +- .../compose/navigation3/SentryNavEffect.kt | 19 +- .../lifecycle/NavActivityWatcher.kt | 111 +++ .../lifecycle/NavLeaseCoordinator.kt | 602 ++++++------ .../navigation3/lifecycle/NavRootInfo.kt | 39 + .../navigation3/lifecycle/NavScopes.kt | 100 +- .../navigation3/lifecycle/NavTransaction.kt | 149 --- .../lifecycle/NavTransactionRequest.kt | 103 +++ .../compose/navigation3/lifecycle/README.md | 219 ++++- .../lifecycle/StagedNavTransaction.kt | 297 +++--- .../navigation3/BackStackObserverTest.kt | 9 +- .../CoordinatedBackStackObserverTest.kt | 153 +++- ...SentryNavEffectLifecycleIntegrationTest.kt | 858 +++++++++++++++++- .../navigation3/SentryNavEffectTest.kt | 33 +- .../navigation3/lifecycle/FindActivityTest.kt | 56 ++ .../lifecycle/NavLeaseCoordinatorTest.kt | 772 +++++++++++++++- .../navigation3/lifecycle/NavScopeTest.kt | 80 +- .../lifecycle/NavScopesIntegrationTest.kt | 12 +- .../navigation3/lifecycle/NavScopesTest.kt | 249 +++-- .../lifecycle/NavTransactionRequestTest.kt | 244 +++++ .../lifecycle/NavTransactionTest.kt | 348 ------- .../lifecycle/StagedNavTransactionTest.kt | 650 ++++++++++--- .../src/main/AndroidManifest.xml | 5 + .../navigation/nav3/Nav3MultiFragment.kt | 17 +- .../navigation/nav3/Nav3PlainScreens.kt | 206 +++++ .../navigation/nav3/Nav3RouteScreens.kt | 1 + .../android/navigation/nav3/Nav3Routes.kt | 4 +- .../navigation/nav3/Nav3TransactionHistory.kt | 16 + 31 files changed, 4162 insertions(+), 1377 deletions(-) create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavActivityWatcher.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavRootInfo.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransaction.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionRequest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/FindActivityTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionRequestTest.kt delete mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionTest.kt create mode 100644 sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PlainScreens.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 76789a90411..cca2f0ab3bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,8 +15,14 @@ - Most SDK log calls no longer allocate when `debug` is off ([#6600](https://github.com/getsentry/sentry-java/pull/6600)) +### Behavioral Changes + +- 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 +- 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)) ## 8.64.0 diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index 6d4f70fc9f1..139158f4bd9 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -47,6 +47,10 @@ android { 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 } @@ -68,7 +72,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/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/BackStackObserverTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackObserverTest.kt index d331afabe69..d7d8895c608 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() } 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..2b8547b4084 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 @@ -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 @@ -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/SentryNavEffectLifecycleIntegrationTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectLifecycleIntegrationTest.kt index d5467b10b9a..145b5c0cf74 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,19 @@ 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.ActivityFramesTracker +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 +66,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 +99,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 +252,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 +545,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 +641,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 +653,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 +784,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 +952,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 +1271,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 +1287,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 +1303,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 +1320,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 +1374,7 @@ class SentryNavEffectLifecycleIntegrationTest { internal class CheckoutFragment : NavEffectFragment("Checkout") + /** A Fragment whose content has no SentryNavEffect. */ internal class PlainFragment : Fragment() { override fun onCreateView( @@ -758,13 +1401,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 +1445,74 @@ 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), + mock(), + ) + 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 +1531,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 +1540,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) ) } - 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..7a0ed005f8e 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 @@ -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..5f8b0ccd003 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()) } @@ -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..fb9782877e2 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 c865e8e91e6..84e1d1822c9 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() @@ -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 = mock() + 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 = mock() + 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")) } @@ -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 = mock() + 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 = mock() + 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 @@ -614,7 +728,7 @@ class NavScopesTest { 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)) @@ -652,12 +766,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]. */ @@ -707,8 +822,12 @@ class NavScopesTest { NoOpTransaction.getInstance() } else { val name = (it.arguments[0] as TransactionContext).name + val contexts = Contexts() mock() - .also { transaction -> whenever(transaction.name).thenReturn(name) } + .also { transaction -> + whenever(transaction.name).thenReturn(name) + whenever(transaction.contexts).thenReturn(contexts) + } .also(startedTransactions::add) } } @@ -743,15 +862,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 @@ -778,3 +895,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 e732db751e9..82c45a1df90 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 = mock().also { whenever(it.isFinished).thenReturn(true) } - private val hostTransaction = mock() + 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() - discards a staged nav transaction blocked by another transaction`() { + fun `publishTo() - leaves the scope untouched without a nav transaction`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - val navTransaction = stagedNavTransaction.stage(transactionContext, transactionOptions) + 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() - starts a nav transaction for a request whose staged one was discarded`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + 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 `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 `publishTo() - forgets an unpublished nav transaction that has finished and keeps another transaction`() { + 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() @@ -518,7 +913,7 @@ class StagedNavTransactionTest { } } - val stagedNavTransaction = StagedNavTransaction(scopes) + val stagedNavTransaction = StagedNavTransaction(scopes, ticker) init { scope.options.addScopeObserver( @@ -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-samples/sentry-samples-android/src/main/AndroidManifest.xml b/sentry-samples/sentry-samples-android/src/main/AndroidManifest.xml index 5b0f8dd715e..3a8c263e0f4 100644 --- a/sentry-samples/sentry-samples-android/src/main/AndroidManifest.xml +++ b/sentry-samples/sentry-samples-android/src/main/AndroidManifest.xml @@ -147,6 +147,11 @@ android:exported="false" android:theme="@style/AppTheme.Main.Translucent" /> + + Unit) { 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/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..6d64c7da45f --- /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..92a7cbbd6bb 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, 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/Nav3TransactionHistory.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TransactionHistory.kt index 21d99a50b2c..c443c9a8bd5 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 @@ -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 -> From 013d0ccd90f4efbebb7259ec3f110dd872b002ae Mon Sep 17 00:00:00 2001 From: Roman Zavarnitsyn Date: Fri, 13 Nov 2026 11:35:54 +0100 Subject: [PATCH 34/51] chore(deps): Scan one Gradle directory with Dependabot (#6603) The separate sample and test builds read the SDK build's version catalog, so listing them as Dependabot directories opened one PR per directory for the same catalog bump. The root directory covers the catalog; the three versions only the samples declared move into it. Co-authored-by: Claude Fable 5.1 --- .github/dependabot.yml | 11 +++++------ gradle/libs.versions.toml | 4 ++++ .../sentry-samples-netflix-dgs/build.gradle.kts | 4 ++-- .../sentry-samples-servlet/build.gradle.kts | 2 +- 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7cee6759bd3..93fc79f4a2f 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -7,12 +7,9 @@ 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: @@ -20,6 +17,8 @@ updates: 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/gradle/libs.versions.toml b/gradle/libs.versions.toml index d6a55ba3d56..deb030f285d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -10,6 +10,7 @@ asyncProfiler = "4.4" camerax = "1.4.0" composeCompiler = "1.5.14" coroutines = "1.6.1" +dgs = "4.9.2" detekt = "1.23.8" dokka = "2.0.0" espresso = "3.7.0" @@ -146,6 +147,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,6 +199,7 @@ retrofit-gson = { module = "com.squareup.retrofit2:converter-gson", version.ref 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" } diff --git a/sentry-samples/sentry-samples-netflix-dgs/build.gradle.kts b/sentry-samples/sentry-samples-netflix-dgs/build.gradle.kts index 7bbc377a286..968feb5a1b7 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") diff --git a/sentry-samples/sentry-samples-servlet/build.gradle.kts b/sentry-samples/sentry-samples-servlet/build.gradle.kts index 5cc8a7e0a4f..e223e8786ec 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_1_8 dependencies { implementation("io.sentry:sentry-servlet:$sentryVersion") - implementation("javax.servlet:javax.servlet-api:4.0.1") + implementation(libs.servlet4.api) } tasks.withType().configureEach { useJUnitPlatform() } From 7f94ff0507ba553e93a234e54e83e0e5e33d67d8 Mon Sep 17 00:00:00 2001 From: Alexander Dinauer Date: Fri, 13 Nov 2026 13:34:30 +0100 Subject: [PATCH 35/51] build(deps): Bump OpenTelemetry to 2.33.1 (#6602) * build(deps): Bump OpenTelemetry to 2.33.1 Align the OpenTelemetry instrumentation and Java agent with SDK 1.67.0. Update tests for the SDK optimization that returns non-recording spans when no span processor is configured. Co-Authored-By: Claude * changelog * changelog * build(deps): Align OpenTelemetry semantic conventions Use the semantic convention versions tested with OpenTelemetry Java instrumentation 2.33.1. Co-Authored-By: Claude * docs(changelog): Clarify OpenTelemetry dependency bump List the semantic convention upgrades and explain how missing span processors affect outgoing Sentry trace headers. Co-Authored-By: Claude --------- Co-authored-by: Claude --- CHANGELOG.md | 10 ++++++ gradle/libs.versions.toml | 12 +++---- .../src/test/kotlin/SentrySamplerTest.kt | 32 ++++++++++++------- .../test/kotlin/OtelSentryPropagatorTest.kt | 12 +++++-- .../src/test/kotlin/OtlpEndToEndTest.kt | 10 +++++- 5 files changed, 55 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cca2f0ab3bb..4f6c22e1d5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,16 @@ - 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)) +### Dependencies + +- 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. + ## 8.64.0 ### Breaking Changes diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index deb030f285d..68a8f191bdb 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -30,13 +30,13 @@ 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" +otelSemanticConventions = "1.44.0" +otelSemanticConventionsAlpha = "1.44.0-alpha" retrofit = "3.0.0" room2 = "2.8.5" room3 = "3.0.0-rc01" 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-otlp/src/test/kotlin/OtelSentryPropagatorTest.kt b/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtelSentryPropagatorTest.kt index afa728c7ff0..d0220daf952 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 @@ -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") @@ -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 fb3db9731e8..ca94bc1fad3 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() { From e7885170773cb3033466e95c998a8a63d55c4979 Mon Sep 17 00:00:00 2001 From: Alexander Dinauer Date: Fri, 13 Nov 2026 13:39:38 +0100 Subject: [PATCH 36/51] build(deps): Prepare for Spring Boot 4.2 (#6532) * build(deps): Bump Spring Boot to 4.2.0-RC2 Align OpenTelemetry with the version managed by Spring Boot 4.2. Keep RestTemplate support compiling despite upstream removal warnings and update tests for OpenTelemetry's no-processor optimization. Co-Authored-By: Claude * changelog * fix(spring): Suppress RestTemplate removal warnings Keep the Spring 7 sample compiling with warnings treated as errors after the Spring Boot 4.2 dependency bump. Co-Authored-By: Claude * build(deps): Add Spring milestone repository Resolve Spring Boot 4.2 release candidate plugin and framework artifacts in clean CI environments. Co-Authored-By: Claude * test(spring): Build valid GraphQL operation documents Include a selection set so GraphQL Java 25 can print the test operations used by Spring subscription error reporting tests. Co-Authored-By: Claude * build(deps): Bump OpenTelemetry to 2.33.1 Align the OpenTelemetry instrumentation and Java agent with SDK 1.67.0. Update tests for the SDK optimization that returns non-recording spans when no span processor is configured. Co-Authored-By: Claude * changelog * build(spring): Keep Spring Boot 4.1 dependency Limit the preparation PR to forward-compatible source and test changes. Remove the Spring Boot 4.2 release candidate bump, milestone repositories, and dependency changelog entry. Co-Authored-By: Claude --------- Co-authored-by: Claude --- .../io/sentry/samples/spring7/WebConfig.java | 1 + .../samples/spring7/web/PersonService.java | 2 + .../spring/boot4/SentryDemoApplication.java | 1 + .../samples/spring/boot4/TodoController.java | 1 + .../spring/boot4/SentryDemoApplication.java | 1 + .../samples/spring/boot4/TodoController.java | 1 + .../spring/boot4/SentryDemoApplication.java | 1 + .../samples/spring/boot4/TodoController.java | 1 + .../boot4/otlp/SentryDemoApplication.java | 1 + .../spring/boot4/otlp/TodoController.java | 1 + .../spring/boot4/SentryDemoApplication.java | 1 + .../samples/spring/boot4/TodoController.java | 1 + .../SentrySpringSubscriptionHandlerTest.kt | 37 +++++++++---------- .../spring/boot4/SentryAutoConfiguration.java | 1 + .../SentrySpanRestTemplateCustomizer.java | 1 + 15 files changed, 32 insertions(+), 20 deletions(-) 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/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..e5f395ec2b5 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; 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..c5093bc9cf5 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; 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..c5093bc9cf5 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; 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..9a4dd98c90b 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; 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..0bbe0643495 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; 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..24f32e77f88 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-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 8562d14f160..734bd5d8a5c 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 @@ -512,6 +512,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/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; From 8dac521886d7675201b2029b6261f44886164b92 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:10:39 +0100 Subject: [PATCH 37/51] chore(deps): bump org.hsqldb:hsqldb from 2.6.1 to 2.7.4 (#6572) Bumps org.hsqldb:hsqldb from 2.6.1 to 2.7.4. --- updated-dependencies: - dependency-name: org.hsqldb:hsqldb dependency-version: 2.7.4 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 68a8f191bdb..962544c6dcd 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -295,7 +295,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" } From 49705437314208a3d29bd0a60ec33e2827e6c417 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:16:01 +0100 Subject: [PATCH 38/51] chore(deps): bump the github-actions group across 1 directory with 4 updates (#6610) Bumps the github-actions group with 4 updates in the / directory: [getsentry/github-workflows/danger](https://github.com/getsentry/github-workflows), [getsentry/craft](https://github.com/getsentry/craft), [getsentry/github-workflows/updater](https://github.com/getsentry/github-workflows) and [getsentry/github-workflows/validate-pr](https://github.com/getsentry/github-workflows). Updates `getsentry/github-workflows/danger` from 3.4.1 to 3.5.0 - [Release notes](https://github.com/getsentry/github-workflows/releases) - [Changelog](https://github.com/getsentry/github-workflows/blob/main/CHANGELOG.md) - [Commits](https://github.com/getsentry/github-workflows/compare/959162c159b866489d3fabe93327f48f9b8cb7ee...36529d71129a14967bea1fb81bcaf2a5943cf877) Updates `getsentry/craft` from 3.11.2 to 3.12.0 - [Release notes](https://github.com/getsentry/craft/releases) - [Changelog](https://github.com/getsentry/craft/blob/master/CHANGELOG.md) - [Commits](https://github.com/getsentry/craft/compare/9567926a606072678ef367b02445c4f99f374795...0da9309228741a4c300d3c87ed7dcafa8f703525) Updates `getsentry/github-workflows/updater` from 3.4.1 to 3.5.0 - [Release notes](https://github.com/getsentry/github-workflows/releases) - [Changelog](https://github.com/getsentry/github-workflows/blob/main/CHANGELOG.md) - [Commits](https://github.com/getsentry/github-workflows/compare/959162c159b866489d3fabe93327f48f9b8cb7ee...36529d71129a14967bea1fb81bcaf2a5943cf877) Updates `getsentry/github-workflows/validate-pr` from 3.4.1 to 3.5.0 - [Release notes](https://github.com/getsentry/github-workflows/releases) - [Changelog](https://github.com/getsentry/github-workflows/blob/main/CHANGELOG.md) - [Commits](https://github.com/getsentry/github-workflows/compare/959162c159b866489d3fabe93327f48f9b8cb7ee...36529d71129a14967bea1fb81bcaf2a5943cf877) --- updated-dependencies: - dependency-name: getsentry/github-workflows/danger dependency-version: 3.5.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: github-actions - dependency-name: getsentry/craft dependency-version: 3.12.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: github-actions - dependency-name: getsentry/github-workflows/updater dependency-version: 3.5.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: github-actions - dependency-name: getsentry/github-workflows/validate-pr dependency-version: 3.5.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: github-actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/danger.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/update-deps.yml | 2 +- .github/workflows/validate-pr.yml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) 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/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 }} From bc46d2782ee43fce095f2418fda97b326222fe86 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:41:04 +0100 Subject: [PATCH 39/51] chore(deps): bump com.github.ben-manes.versions from 0.42.0 to 0.67.0 (#6573) Bumps com.github.ben-manes.versions from 0.42.0 to 0.67.0. --- updated-dependencies: - dependency-name: com.github.ben-manes.versions dependency-version: 0.67.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 962544c6dcd..00630261065 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -73,7 +73,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" } From 8b7119fa203385faed534f5974646bc5875aa56f Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Mon, 16 Nov 2026 10:09:43 +0100 Subject: [PATCH 40/51] build(deps): Bump Spotless to 8.11.0 (#6612) * build(deps): Bump Spotless to 8.11.0 Spotless 8.11.0 bumps the default google-java-format from 1.28.0 to 2.0.0 and ktfmt from 0.63 to 0.65, so this also reformats the codebase with make format. Co-Authored-By: Claude Opus 5.5 * build(android): Update detekt baseline for ktfmt trailing commas Detekt baseline IDs embed the flagged code, so the trailing commas ktfmt 0.65 adds no longer matched two entries in sentry-android-distribution. Co-Authored-By: Claude Opus 5.5 * ref(distribution): Use check, require and error instead of throwing Fixes the UseCheckOrError and UseRequire detekt issues instead of keeping them in the baseline. The thrown exception types and messages stay the same. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- gradle/libs.versions.toml | 2 +- .../android/core/ActivityFramesTracker.java | 19 +- .../core/ActivityLifecycleIntegration.java | 92 ++-- .../core/AndroidContinuousProfiler.java | 33 +- .../sentry/android/core/AnrIntegration.java | 15 +- .../io/sentry/android/core/ContextUtils.java | 107 ++-- .../core/EnvelopeFileObserverIntegration.java | 15 +- .../core/FeedbackShakeIntegration.java | 44 +- .../android/core/InternalSentrySdk.java | 91 ++-- .../sentry/android/core/LifecycleWatcher.java | 17 +- .../core/PerfettoContinuousProfiler.java | 23 +- .../core/SendCachedEnvelopeIntegration.java | 108 ++-- .../io/sentry/android/core/SentryAndroid.java | 13 +- .../android/core/SentryShakeDetector.java | 9 +- .../core/SentryUserFeedbackButton.java | 13 +- .../android/core/SentryUserFeedbackForm.java | 219 ++++---- .../android/core/SentryWebViewTracing.java | 41 +- .../core/SpanFrameMetricsCollector.java | 31 +- .../SystemEventsBreadcrumbsIntegration.java | 87 ++- .../core/ViewHierarchyEventProcessor.java | 17 +- .../core/anr/AnrProfilingIntegration.java | 23 +- .../core/cache/AndroidEnvelopeCache.java | 2 +- .../gestures/SentryGestureListener.java | 56 +- .../internal/modules/AssetsModulesLoader.java | 7 +- .../util/AndroidConnectionStatusProvider.java | 91 ++-- .../internal/util/FirstDrawDoneListener.java | 13 +- .../core/internal/util/ScreenshotMasking.java | 15 +- .../core/internal/util/ScreenshotUtils.java | 19 +- .../util/SentryFrameMetricsCollector.java | 87 ++- .../core/performance/AppStartMetrics.java | 29 +- .../io/sentry/android/core/ANRWatchDogTest.kt | 6 +- .../core/ActivityLifecycleIntegrationTest.kt | 16 +- .../core/AndroidContinuousProfilerTest.kt | 2 +- .../core/AndroidOptionsInitializerTest.kt | 46 +- .../android/core/AndroidProfilerTest.kt | 4 +- .../android/core/AndroidTransportGateTest.kt | 4 +- .../android/core/AnrV2IntegrationTest.kt | 4 +- .../core/AppLifecycleIntegrationTest.kt | 6 +- .../android/core/AppStartExtensionTest.kt | 6 +- .../io/sentry/android/core/AppStateTest.kt | 6 +- ...ApplicationExitInfoCrossIntegrationTest.kt | 6 +- .../ApplicationExitInfoEventProcessorTest.kt | 54 +- .../ApplicationExitIntegrationTestBase.kt | 2 +- .../sentry/android/core/ContextUtilsTest.kt | 22 +- .../android/core/ContextUtilsTestHelper.kt | 5 +- .../core/DefaultAndroidEventProcessorTest.kt | 20 +- .../sentry/android/core/DeviceInfoUtilTest.kt | 2 +- .../EnvelopeFileObserverIntegrationTest.kt | 2 +- .../core/FeedbackShakeIntegrationTest.kt | 2 +- .../android/core/InternalSentrySdkTest.kt | 40 +- .../android/core/LifecycleWatcherTest.kt | 4 +- .../core/ManifestMetadataReaderTest.kt | 29 +- .../core/NetworkBreadcrumbsIntegrationTest.kt | 6 +- .../core/PerfettoContinuousProfilerTest.kt | 2 +- .../android/core/PerfettoProfilerTest.kt | 2 +- .../PerformanceAndroidEventProcessorTest.kt | 18 +- .../core/ScreenshotEventProcessorTest.kt | 14 +- .../core/SendCachedEnvelopeIntegrationTest.kt | 2 +- .../android/core/SentryAndroidOptionsTest.kt | 6 +- .../sentry/android/core/SentryAndroidTest.kt | 6 +- .../core/SentryPerformanceProviderTest.kt | 4 +- .../core/SentryRootCaSslSocketFactoryTest.kt | 2 +- .../core/SentryScreenshotOptionsTest.kt | 4 +- .../core/SentryUserFeedbackFormTest.kt | 4 +- .../android/core/SentryWebViewTracingTest.kt | 6 +- .../core/SpanFrameMetricsCollectorTest.kt | 4 +- .../SystemEventsBreadcrumbsIntegrationTest.kt | 22 +- .../android/core/TombstoneIntegrationTest.kt | 4 +- .../core/UserInteractionIntegrationTest.kt | 4 +- .../core/WebViewTracePropagationScriptTest.kt | 12 +- .../core/cache/AndroidEnvelopeCacheTest.kt | 14 +- .../debugmeta/AssetsDebugMetaLoaderTest.kt | 4 +- .../SentryGestureListenerTracingTest.kt | 2 +- .../modules/AssetsModulesLoaderTest.kt | 6 +- .../threaddump/ThreadDumpParserTest.kt | 12 +- .../internal/tombstone/TombstoneParserTest.kt | 58 +- ...ConnectionStatusProviderConcurrencyTest.kt | 6 +- .../AndroidConnectionStatusProviderTest.kt | 14 +- .../CellularNetworkTechnologyProviderTest.kt | 32 +- .../core/internal/util/RootCheckerTest.kt | 4 +- .../ScreenshotUtilsMaskedScreenshotTest.kt | 2 +- .../core/performance/AppStartMetricsTest.kt | 2 +- .../performance/AppStartMetricsTestApi35.kt | 6 +- sentry-android-distribution/build.gradle.kts | 2 +- .../detekt-baseline.xml | 4 - .../distribution/DistributionHttpClient.kt | 10 +- .../distribution/DistributionIntegration.kt | 2 +- .../distribution/UpdateResponseParser.kt | 6 +- .../distribution/UpdateResponseParserTest.kt | 2 +- .../fragment/FragmentLifecycleIntegration.kt | 2 +- .../SentryFragmentLifecycleCallbacksTest.kt | 2 +- .../critical/EmptyBroadcastReceiver.kt | 6 +- .../uitest/android/critical/MainActivity.kt | 10 +- .../uitest/android/AutomaticSpansTest.kt | 12 +- .../io/sentry/uitest/android/EnvelopeTests.kt | 12 +- .../io/sentry/uitest/android/ReplayTest.kt | 8 +- .../io/sentry/uitest/android/SdkInitTests.kt | 31 +- .../uitest/android/UserFeedbackUiTest.kt | 30 +- .../uitest/android/UserInteractionTests.kt | 6 +- .../android/mockservers/RelayAsserter.kt | 4 +- .../sentry/uitest/android/ComposeActivity.kt | 2 +- .../uitest/android/ProfilingSampleActivity.kt | 2 +- .../navigation3/BackStackEntryMapper.kt | 2 +- .../navigation3/BackStackConverterTest.kt | 44 +- .../navigation3/BackStackObserverTest.kt | 26 +- .../CoordinatedBackStackObserverTest.kt | 14 +- .../ForwardingBackStackEntryMapperTest.kt | 12 +- ...SentryNavEffectLifecycleIntegrationTest.kt | 4 +- .../navigation3/SentryNavEffectTest.kt | 10 +- .../navigation3/lifecycle/NavScopeTest.kt | 4 +- .../lifecycle/NavScopesIntegrationTest.kt | 2 +- .../navigation3/lifecycle/NavScopesTest.kt | 10 +- .../lifecycle/StagedNavTransactionTest.kt | 12 +- .../android/ndk/outproc/NativeBackendTest.kt | 10 +- .../ndk/outproc/SentryNdkCrashServiceTest.kt | 2 +- .../sentry/android/ndk/NdkScopeObserver.java | 74 ++- .../io/sentry/android/ndk/SentryNdkTest.kt | 6 +- .../sentry/android/ndk/SentryNdkUtilTest.kt | 2 +- .../DefaultReplayBreadcrumbConverter.kt | 6 +- .../android/replay/ReplayIntegration.kt | 8 +- .../sentry/android/replay/WindowRecorder.kt | 2 +- .../replay/capture/BaseCaptureStrategy.kt | 2 +- .../replay/capture/BufferCaptureStrategy.kt | 6 +- .../replay/capture/SessionCaptureStrategy.kt | 4 +- .../replay/gestures/ReplayGestureConverter.kt | 6 +- .../replay/screenshot/CanvasStrategy.kt | 2 +- .../replay/screenshot/PixelCopyStrategy.kt | 6 +- .../replay/AnrWithReplayIntegrationTest.kt | 8 +- .../DefaultReplayBreadcrumbConverterTest.kt | 16 +- .../replay/PreviousReplayIntegrationTest.kt | 4 +- .../sentry/android/replay/ReplayCacheTest.kt | 16 +- .../android/replay/ReplayIntegrationTest.kt | 4 +- .../sentry/android/replay/ReplaySmokeTest.kt | 2 +- .../capture/BufferCaptureStrategyTest.kt | 6 +- .../capture/SessionCaptureStrategyTest.kt | 2 +- .../replay/gestures/GestureRecorderTest.kt | 6 +- .../gestures/ReplayGestureConverterTest.kt | 2 +- .../screenshot/PixelCopyStrategyTest.kt | 2 +- .../ComposeMaskingOptionsTest.kt | 2 +- .../ContainerMaskingOptionsTest.kt | 16 +- .../timber/SentryTimberIntegrationTest.kt | 4 +- .../android/timber/SentryTimberTreeTest.kt | 10 +- ...acheHttpClientTransportClientReportTest.kt | 2 +- .../ApacheHttpClientTransportFactoryTest.kt | 2 +- .../apollo3/SentryApolloBuilderExtensions.kt | 2 +- .../SentryApollo3InterceptorClientErrors.kt | 6 +- .../apollo3/SentryApollo3InterceptorTest.kt | 14 +- ...ntryApollo3InterceptorWithVariablesTest.kt | 2 +- .../LaunchDetailsQuerySelections.kt | 2 +- .../apollo4/SentryApolloBuilderExtensions.kt | 2 +- ...pollo4BuilderExtensionsClientErrorsTest.kt | 8 +- .../SentryApollo4BuilderExtensionsTest.kt | 4 +- .../SentryApollo4HttpInterceptorTest.kt | 16 +- .../apollo5/SentryApollo5HttpInterceptor.kt | 2 +- .../apollo5/SentryApolloBuilderExtensions.kt | 2 +- ...pollo5BuilderExtensionsClientErrorsTest.kt | 8 +- .../SentryApollo5BuilderExtensionsTest.kt | 16 +- .../SentryApollo5HttpInterceptorTest.kt | 16 +- .../LaunchDetailsQuerySelections.kt | 10 +- .../apollo/SentryApolloInterceptorTest.kt | 4 +- .../profiling/JavaContinuousProfiler.java | 33 +- .../profiling/JavaContinuousProfilerTest.kt | 2 +- sentry-compose/build.gradle.kts | 6 +- .../compose/SentryNavigationIntegration.kt | 4 +- .../sentry/compose/ComposeIntegrationTests.kt | 2 +- .../compose/SentryModifierComposeTest.kt | 4 +- .../io/sentry/compose/SentryTracedTest.kt | 6 +- .../ComposeGestureTargetLocatorTest.kt | 6 +- .../ComposeViewHierarchyExporterTest.kt | 2 +- .../graphql22/SentryInstrumentation.java | 7 +- .../SentryInstrumentationAnotherTest.kt | 18 +- .../graphql22/SentryInstrumentationTest.kt | 14 +- .../io/sentry/graphql/ExceptionReporter.java | 13 +- .../graphql/SentryGraphqlInstrumentation.java | 19 +- .../sentry/graphql/ExceptionReporterTest.kt | 2 +- ...yGenericDataFetcherExceptionHandlerTest.kt | 2 +- .../SentryGraphqlInstrumentationTest.kt | 6 +- .../sentry/graphql/SentryInstrumentation.java | 7 +- .../SentryInstrumentationAnotherTest.kt | 18 +- .../graphql/SentryInstrumentationTest.kt | 14 +- .../sentry/jcache/SentryJCacheWrapperTest.kt | 4 +- .../io/sentry/jdbc/DatabaseUtilsTest.kt | 22 +- .../kotlin/io/sentry/jul/SentryHandlerTest.kt | 16 +- .../kotlin/SentryCoroutineExceptionHandler.kt | 2 +- .../io/sentry/kotlin/SentryContextTest.kt | 20 +- .../SentryCoroutineExceptionHandlerTest.kt | 2 +- .../ktorClient/SentryKtorClientPlugin.kt | 2 +- .../ktorClient/SentryKtorClientPluginTest.kt | 14 +- sentry-log4j2/build.gradle.kts | 2 +- .../io/sentry/log4j2/SentryAppenderTest.kt | 14 +- .../io/sentry/logback/SentryAppenderTest.kt | 28 +- .../okhttp/SentryOkHttpEventListener.kt | 4 +- .../sentry/okhttp/SentryOkHttpInterceptor.kt | 6 +- .../okhttp/SentryOkHttpEventListenerTest.kt | 2 +- .../io/sentry/okhttp/SentryOkHttpEventTest.kt | 2 +- .../okhttp/SentryOkHttpInterceptorTest.kt | 34 +- ...HttpInterceptorUnknownContentLengthTest.kt | 8 +- .../io/sentry/okhttp/SentryOkHttpUtilsTest.kt | 2 +- .../sentry/openfeign/SentryFeignClientTest.kt | 12 +- .../build.gradle.kts | 2 +- ...ryAutoConfigurationCustomizerProvider.java | 17 +- .../agentless/AgentlessEndToEndTest.kt | 6 +- .../OpenTelemetryAttributesExtractor.java | 41 +- .../OtelSentrySpanProcessor.java | 12 +- .../sentry/opentelemetry/SentrySampler.java | 13 +- .../opentelemetry/SentrySpanExporter.java | 27 +- .../opentelemetry/SentrySpanProcessor.java | 23 +- .../OpenTelemetryAttributesExtractorTest.kt | 32 +- .../OtelInternalSpanDetectionUtilTest.kt | 4 +- .../test/kotlin/OtelSentryPropagatorTest.kt | 20 +- .../src/test/kotlin/OtelSpanWrapperTest.kt | 2 +- .../test/kotlin/SentrySpanProcessorTest.kt | 2 +- .../kotlin/SpanDescriptionExtractorTest.kt | 38 +- .../test/kotlin/OtelSentryPropagatorTest.kt | 4 +- .../src/test/kotlin/OtlpEndToEndTest.kt | 2 +- .../io/sentry/quartz/SentryJobListenerTest.kt | 4 +- .../sentry-samples-android/build.gradle.kts | 6 +- .../android/FrameDataForSpansActivity.kt | 8 +- .../io/sentry/samples/android/GithubAPI.kt | 2 +- .../io/sentry/samples/android/MainActivity.kt | 103 ++-- .../samples/android/ProfilingActivity.kt | 4 +- .../android/ReplayAnimationsActivity.kt | 4 +- .../sentry/samples/android/SecondActivity.kt | 2 +- .../sentry/samples/android/ThirdFragment.kt | 2 +- .../android/TriggerHttpRequestActivity.java | 20 +- .../sentry/samples/android/WebViewActivity.kt | 2 +- .../android/memory/MemoryLimiterActivity.kt | 6 +- .../common/NavigationRouteWorkDialog.kt | 4 +- .../android/navigation/common/RouteWorkApi.kt | 4 +- .../android/navigation/nav2/Nav2Activity.kt | 10 +- .../navigation/nav2/Nav2ComposeRoutes.kt | 6 +- .../navigation/nav2/Nav2ModalFragments.kt | 18 +- .../navigation/nav2/Nav2RouteFragment.kt | 20 +- .../nav2/Nav2SampleConfigAdapter.kt | 2 +- .../android/navigation/nav2/Nav2TopBar.kt | 8 +- .../navigation/nav2/Nav2TransactionHistory.kt | 6 +- .../nav2/Nav2TransactionHistorySheet.kt | 4 +- .../android/navigation/nav3/Nav3Activity.kt | 8 +- .../nav3/Nav3BottomSheetSceneStrategy.kt | 2 +- .../navigation/nav3/Nav3MultiActivity.kt | 12 +- .../navigation/nav3/Nav3MultiFragment.kt | 8 +- .../nav3/Nav3PerformanceControls.kt | 4 +- .../navigation/nav3/Nav3PlainScreens.kt | 6 +- .../navigation/nav3/Nav3RouteScreens.kt | 10 +- .../navigation/nav3/Nav3SampleConfig.kt | 2 +- .../android/navigation/nav3/Nav3TopBar.kt | 4 +- .../navigation/nav3/Nav3TransactionHistory.kt | 12 +- .../nav3/Nav3TransactionHistorySheet.kt | 6 +- .../samples/android/sqlite/SampleDatabases.kt | 6 +- .../samples/android/sqlite/SqlStatements.kt | 2 +- .../samples/android/sqlite/UiLoadScreen.kt | 3 +- .../java/io/sentry/samples/console/Main.java | 39 +- .../java/io/sentry/samples/console/Main.java | 238 ++++---- .../java/io/sentry/samples/console/Main.java | 203 ++++--- .../sentry-samples-log4j2/build.gradle.kts | 2 +- .../build.gradle.kts | 2 +- .../samples/netflix/dgs/ActorsDataloader.java | 21 +- .../samples/netflix/dgs/ShowsDatafetcher.java | 16 +- .../io/sentry/samples/openfeign/Main.java | 35 +- .../samples/servlet/SentryInitializer.java | 111 ++-- .../spring7/SecurityConfiguration.java | 6 +- .../spring/boot4/SecurityConfiguration.java | 6 +- .../samples/spring/boot4/TodoController.java | 15 +- .../boot4/graphql/AssigneeController.java | 27 +- .../boot4/graphql/ProjectController.java | 15 +- .../boot4/graphql/TaskCreatorController.java | 28 +- .../spring/boot4/SecurityConfiguration.java | 6 +- .../samples/spring/boot4/TodoController.java | 15 +- .../boot4/graphql/AssigneeController.java | 27 +- .../boot4/graphql/ProjectController.java | 15 +- .../boot4/graphql/TaskCreatorController.java | 26 +- .../spring/boot4/SecurityConfiguration.java | 6 +- .../samples/spring/boot4/TodoController.java | 15 +- .../boot4/graphql/AssigneeController.java | 27 +- .../boot4/graphql/ProjectController.java | 15 +- .../boot4/graphql/TaskCreatorController.java | 26 +- .../boot4/otlp/SecurityConfiguration.java | 6 +- .../spring/boot4/otlp/TodoController.java | 15 +- .../otlp/graphql/AssigneeController.java | 27 +- .../boot4/otlp/graphql/ProjectController.java | 15 +- .../otlp/graphql/TaskCreatorController.java | 28 +- .../samples/spring/boot4/PersonService.java | 7 +- .../spring/boot4/SecurityConfiguration.java | 6 +- .../samples/spring/boot4/TodoController.java | 15 +- .../boot4/graphql/AssigneeController.java | 27 +- .../boot4/graphql/ProjectController.java | 15 +- .../boot4/graphql/TaskCreatorController.java | 28 +- .../spring/boot/jakarta/TodoController.java | 15 +- .../jakarta/graphql/AssigneeController.java | 27 +- .../jakarta/graphql/ProjectController.java | 15 +- .../graphql/TaskCreatorController.java | 28 +- .../spring/boot/jakarta/TodoController.java | 15 +- .../jakarta/graphql/AssigneeController.java | 27 +- .../jakarta/graphql/ProjectController.java | 15 +- .../graphql/TaskCreatorController.java | 26 +- .../spring/boot/jakarta/TodoController.java | 15 +- .../jakarta/graphql/AssigneeController.java | 27 +- .../jakarta/graphql/ProjectController.java | 15 +- .../graphql/TaskCreatorController.java | 26 +- .../spring/boot/jakarta/TodoController.java | 15 +- .../jakarta/graphql/AssigneeController.java | 27 +- .../jakarta/graphql/ProjectController.java | 15 +- .../graphql/TaskCreatorController.java | 28 +- .../build.gradle.kts | 2 +- .../boot/graphql/AssigneeController.java | 27 +- .../boot/graphql/ProjectController.java | 15 +- .../boot/graphql/TaskCreatorController.java | 26 +- .../build.gradle.kts | 2 +- .../boot/graphql/AssigneeController.java | 27 +- .../boot/graphql/ProjectController.java | 15 +- .../boot/graphql/TaskCreatorController.java | 26 +- .../spring/boot/jakarta/PersonService.java | 7 +- .../build.gradle.kts | 2 +- .../build.gradle.kts | 2 +- .../boot/graphql/AssigneeController.java | 27 +- .../boot/graphql/ProjectController.java | 15 +- .../boot/graphql/TaskCreatorController.java | 26 +- .../jakarta/SentryServletRequestListener.java | 9 +- .../SentryServletContainerInitializerTest.kt | 2 +- .../servlet/SentryServletRequestListener.java | 9 +- .../SentryServletContainerInitializerTest.kt | 2 +- .../integrationtest/MetricsIntegrationTest.kt | 2 +- .../io/sentry/spring7/SentrySpringFilter.java | 33 +- .../spring7/cache/SentryCacheWrapper.java | 44 +- .../graphql/SentryBatchLoaderRegistry.java | 22 +- .../graphql/SentryDgsSubscriptionHandler.java | 11 +- .../SentrySpringSubscriptionHandler.java | 20 +- .../SentrySpanClientWebRequestFilter.java | 39 +- .../webflux/AbstractSentryWebFilter.java | 7 +- .../webflux/SentryWebExceptionHandler.java | 40 +- .../spring7/webflux/SentryWebFilter.java | 9 +- ...entryWebFilterWithThreadLocalAccessor.java | 24 +- .../io/sentry/spring7/EnableSentryTest.kt | 6 +- .../sentry/spring7/SentryCheckInAdviceTest.kt | 2 +- .../sentry/spring7/SentrySpringFilterTest.kt | 4 +- .../sentry/spring7/SentryTaskDecoratorTest.kt | 2 +- .../io/sentry/spring7/SentryUserFilterTest.kt | 10 +- .../TransactionNameProviderUtilsTest.kt | 2 +- .../checkin/SentryScheduledCheckInTest.kt | 10 +- .../SentrySpringSubscriptionHandlerTest.kt | 4 +- ...entryKafkaProducerBeanPostProcessorTest.kt | 4 +- ...trySpanClientHttpRequestInterceptorTest.kt | 2 +- .../tracing/SentryTracingFilterTest.kt | 15 +- .../tracing/SentryTransactionAdviceTest.kt | 2 +- .../spring7/webflux/SentryScheduleHookTest.kt | 2 +- .../webflux/SentryWebFluxTracingFilterTest.kt | 11 +- .../webflux/SentryWebfluxIntegrationTest.kt | 2 +- .../boot4/agentfixture/TodoController.kt | 2 +- .../integrationtest/GraphqlIntegrationTest.kt | 2 +- .../integrationtest/MetricsIntegrationTest.kt | 2 +- .../integrationtest/PersonIntegrationTest.kt | 6 +- .../boot4/integrationtest/TodoController.kt | 2 +- .../integrationtest/TodoIntegrationTest.kt | 2 +- .../otelagentintegrationtest/AgentApp.kt | 4 +- .../GraphqlIntegrationTest.kt | 2 +- .../MetricsIntegrationTest.kt | 2 +- .../PersonIntegrationTest.kt | 8 +- .../TodoIntegrationTest.kt | 2 +- .../GraphqlIntegrationTest.kt | 2 +- .../MetricsIntegrationTest.kt | 2 +- .../PersonIntegrationTest.kt | 6 +- .../TodoController.kt | 2 +- .../TodoIntegrationTest.kt | 2 +- .../GraphqlIntegrationTest.kt | 2 +- .../MetricsIntegrationTest.kt | 2 +- .../PersonIntegrationTest.kt | 6 +- .../otlpintegrationtest/TodoController.kt | 2 +- .../TodoIntegrationTest.kt | 2 +- .../MetricsWebfluxIntegrationTest.kt | 2 +- .../TodoWebfluxIntegrationTest.kt | 2 +- .../spring/boot4/SentryAutoConfiguration.java | 11 +- .../boot4/SentryLogbackInitializer.java | 35 +- .../boot4/SentrySpanRestClientCustomizer.java | 17 +- .../boot4/SentryAutoConfigurationTest.kt | 38 +- ...ntryLog4j2AppenderAutoConfigurationTest.kt | 6 +- ...tryLogbackAppenderAutoConfigurationTest.kt | 6 +- .../SentryOkHttpAutoConfigurationTest.kt | 2 +- .../SentrySpanRestClientCustomizerTest.kt | 10 +- .../SentrySpanRestTemplateCustomizerTest.kt | 10 +- .../SentryWebfluxAutoConfigurationTest.kt | 6 +- .../jakarta/agentfixture/TodoController.kt | 2 +- .../integrationtest/FeatureFlagController.kt | 4 +- .../FeatureFlagIntegrationTest.kt | 4 +- .../integrationtest/GraphqlIntegrationTest.kt | 2 +- .../integrationtest/MetricsIntegrationTest.kt | 2 +- .../integrationtest/PersonIntegrationTest.kt | 6 +- .../jakarta/integrationtest/TodoController.kt | 2 +- .../integrationtest/TodoIntegrationTest.kt | 2 +- .../otelagentintegrationtest/AgentApp.kt | 4 +- .../GraphqlIntegrationTest.kt | 2 +- .../MetricsIntegrationTest.kt | 2 +- .../PersonIntegrationTest.kt | 8 +- .../TodoIntegrationTest.kt | 2 +- .../GraphqlIntegrationTest.kt | 2 +- .../MetricsIntegrationTest.kt | 2 +- .../PersonIntegrationTest.kt | 6 +- .../TodoController.kt | 2 +- .../TodoIntegrationTest.kt | 2 +- .../MetricsWebfluxIntegrationTest.kt | 2 +- .../TodoWebfluxIntegrationTest.kt | 2 +- .../boot/jakarta/SentryAutoConfiguration.java | 11 +- .../jakarta/SentryLogbackInitializer.java | 35 +- .../SentrySpanRestClientCustomizer.java | 17 +- .../jakarta/SentryAutoConfigurationTest.kt | 38 +- ...ntryLog4j2AppenderAutoConfigurationTest.kt | 6 +- ...tryLogbackAppenderAutoConfigurationTest.kt | 6 +- .../SentryOkHttpAutoConfigurationTest.kt | 2 +- .../SentrySpanRestClientCustomizerTest.kt | 10 +- .../SentrySpanRestTemplateCustomizerTest.kt | 10 +- .../SentryWebfluxAutoConfigurationTest.kt | 6 +- .../integrationtest/GraphqlIntegrationTest.kt | 2 +- .../integrationtest/MetricsIntegrationTest.kt | 2 +- .../integrationtest/PersonIntegrationTest.kt | 6 +- .../integrationtest/TodoIntegrationTest.kt | 2 +- .../boot/otelagentintegrationtest/AgentApp.kt | 2 +- .../GraphqlIntegrationTest.kt | 2 +- .../KafkaOtelCoexistenceIntegrationTest.kt | 2 +- .../MetricsIntegrationTest.kt | 2 +- .../PersonIntegrationTest.kt | 8 +- .../TodoIntegrationTest.kt | 2 +- .../GraphqlIntegrationTest.kt | 2 +- .../KafkaOtelCoexistenceIntegrationTest.kt | 2 +- .../MetricsIntegrationTest.kt | 2 +- .../PersonIntegrationTest.kt | 6 +- .../TodoIntegrationTest.kt | 2 +- .../MetricsWebfluxIntegrationTest.kt | 2 +- .../TodoWebfluxIntegrationTest.kt | 2 +- .../spring/boot/SentryAutoConfiguration.java | 11 +- .../spring/boot/SentryLogbackInitializer.java | 35 +- .../boot/SentryAutoConfigurationTest.kt | 36 +- ...tryLogbackAppenderAutoConfigurationTest.kt | 6 +- .../boot/SentryOkHttpAutoConfigurationTest.kt | 2 +- .../SentrySpanRestTemplateCustomizerTest.kt | 10 +- .../SentryWebfluxAutoConfigurationTest.kt | 6 +- .../integrationtest/MetricsIntegrationTest.kt | 2 +- .../spring/jakarta/SentrySpringFilter.java | 33 +- .../jakarta/cache/SentryCacheWrapper.java | 44 +- .../graphql/SentryBatchLoaderRegistry.java | 22 +- .../graphql/SentryDgsSubscriptionHandler.java | 11 +- .../SentrySpringSubscriptionHandler.java | 20 +- .../SentrySpanClientWebRequestFilter.java | 39 +- .../webflux/AbstractSentryWebFilter.java | 7 +- .../webflux/SentryWebExceptionHandler.java | 40 +- .../jakarta/webflux/SentryWebFilter.java | 9 +- ...entryWebFilterWithThreadLocalAccessor.java | 24 +- .../sentry/spring/jakarta/EnableSentryTest.kt | 6 +- .../spring/jakarta/SentryCheckInAdviceTest.kt | 2 +- .../spring/jakarta/SentrySpringFilterTest.kt | 4 +- .../spring/jakarta/SentryTaskDecoratorTest.kt | 2 +- .../spring/jakarta/SentryUserFilterTest.kt | 10 +- .../TransactionNameProviderUtilsTest.kt | 2 +- .../checkin/SentryScheduledCheckInTest.kt | 10 +- .../SentrySpringSubscriptionHandlerTest.kt | 4 +- ...entryKafkaProducerBeanPostProcessorTest.kt | 4 +- ...trySpanClientHttpRequestInterceptorTest.kt | 2 +- .../tracing/SentryTracingFilterTest.kt | 15 +- .../tracing/SentryTransactionAdviceTest.kt | 2 +- .../jakarta/webflux/SentryScheduleHookTest.kt | 2 +- .../webflux/SentryWebFluxTracingFilterTest.kt | 11 +- .../webflux/SentryWebfluxIntegrationTest.kt | 2 +- .../integrationtest/MetricsIntegrationTest.kt | 2 +- .../io/sentry/spring/SentrySpringFilter.java | 33 +- .../graphql/SentryBatchLoaderRegistry.java | 22 +- .../graphql/SentryDgsSubscriptionHandler.java | 11 +- .../SentrySpringSubscriptionHandler.java | 20 +- .../SentrySpanClientWebRequestFilter.java | 39 +- .../spring/webflux/SentryWebFilter.java | 74 ++- .../io/sentry/spring/EnableSentryTest.kt | 6 +- .../sentry/spring/SentryCheckInAdviceTest.kt | 2 +- .../sentry/spring/SentrySpringFilterTest.kt | 4 +- .../sentry/spring/SentryTaskDecoratorTest.kt | 2 +- .../io/sentry/spring/SentryUserFilterTest.kt | 10 +- .../TransactionNameProviderUtilsTest.kt | 2 +- .../checkin/SentryScheduledCheckInTest.kt | 10 +- .../SentrySpringSubscriptionHandlerTest.kt | 4 +- ...entryKafkaProducerBeanPostProcessorTest.kt | 4 +- ...trySpanClientHttpRequestInterceptorTest.kt | 2 +- .../spring/tracing/SentryTracingFilterTest.kt | 15 +- .../tracing/SentryTransactionAdviceTest.kt | 2 +- .../spring/webflux/SentryScheduleHookTest.kt | 2 +- .../webflux/SentryWebFluxTracingFilterTest.kt | 11 +- .../webflux/SentryWebfluxIntegrationTest.kt | 2 +- .../src/main/kotlin/io/sentry/Assertions.kt | 4 +- .../kotlin/io/sentry/test/MockSentryServer.kt | 2 +- .../main/java/io/sentry/EnvelopeSender.java | 6 +- .../src/main/java/io/sentry/OutboxSender.java | 4 +- sentry/src/main/java/io/sentry/Scopes.java | 12 +- ...achedEnvelopeFireAndForgetIntegration.java | 107 ++-- sentry/src/main/java/io/sentry/Sentry.java | 189 ++++--- .../src/main/java/io/sentry/SentryClient.java | 73 ++- .../java/io/sentry/SentryEnvelopeItem.java | 507 +++++++++--------- .../io/sentry/SentryStackTraceFactory.java | 4 +- .../src/main/java/io/sentry/SentryTracer.java | 58 +- .../io/sentry/ShutdownHookIntegration.java | 11 +- .../sentry/cache/PersistingScopeObserver.java | 117 ++-- .../AtomicClientReportStorage.java | 29 +- .../file/SentryFileInputStream.java | 11 +- .../file/SentryFileOutputStream.java | 27 +- .../protocol/TransactionNameSource.java | 10 +- .../sentry/transport/AsyncHttpTransport.java | 8 +- .../java/io/sentry/transport/RateLimiter.java | 2 +- .../main/java/io/sentry/util/HintUtils.java | 2 +- .../src/main/java/io/sentry/util/Random.java | 1 - .../java/io/sentry/util/TracingUtils.java | 41 +- sentry/src/test/java/io/sentry/BaggageTest.kt | 8 +- .../io/sentry/CheckInSerializationTest.kt | 4 +- .../io/sentry/CombinedContextsViewTest.kt | 6 +- .../java/io/sentry/CombinedScopeViewTest.kt | 8 +- .../src/test/java/io/sentry/DateUtilsTest.kt | 2 +- ...uplicateMultithreadedEventProcessorTest.kt | 2 +- ...efaultCompositePerformanceCollectorTest.kt | 8 +- sentry/src/test/java/io/sentry/DsnUtilTest.kt | 4 +- ...plicateEventDetectionEventProcessorTest.kt | 4 +- .../test/java/io/sentry/EnvelopeSenderTest.kt | 10 +- .../java/io/sentry/ExternalOptionsTest.kt | 18 +- .../io/sentry/JsonObjectDeserializerTest.kt | 2 +- .../java/io/sentry/JsonObjectReaderTest.kt | 2 +- .../test/java/io/sentry/JsonSerializerTest.kt | 36 +- .../io/sentry/JsonUnknownSerializationTest.kt | 7 +- .../NoOpConnectionStatusProviderTest.kt | 4 +- .../java/io/sentry/NoOpTransactionTest.kt | 8 +- .../java/io/sentry/OptionsContainerTest.kt | 2 +- .../io/sentry/PreviousSessionFinalizerTest.kt | 14 +- sentry/src/test/java/io/sentry/ScopeTest.kt | 6 +- sentry/src/test/java/io/sentry/ScopesTest.kt | 30 +- ...hedEnvelopeFireAndForgetIntegrationTest.kt | 2 +- .../test/java/io/sentry/SentryClientTest.kt | 62 +-- .../SentryClientTransactionProfileTest.kt | 2 +- .../test/java/io/sentry/SentryEndToEndTest.kt | 6 +- .../java/io/sentry/SentryEnvelopeItemTest.kt | 16 +- .../test/java/io/sentry/SentryEventTest.kt | 6 +- .../io/sentry/SentryExceptionFactoryTest.kt | 6 +- .../test/java/io/sentry/SentryOptionsTest.kt | 8 +- .../io/sentry/SentryStackTraceFactoryTest.kt | 12 +- sentry/src/test/java/io/sentry/SentryTest.kt | 8 +- .../java/io/sentry/SentryThreadFactoryTest.kt | 8 +- .../test/java/io/sentry/SentryTracerTest.kt | 94 ++-- .../test/java/io/sentry/SentryWrapperTest.kt | 12 +- sentry/src/test/java/io/sentry/SpanTest.kt | 8 +- sentry/src/test/java/io/sentry/StackTest.kt | 4 +- .../test/java/io/sentry/TracesSamplerTest.kt | 38 +- ...UncaughtExceptionHandlerIntegrationTest.kt | 20 +- .../PersistingScopeObserverBatchingTest.kt | 2 +- .../cache/PersistingScopeObserverTest.kt | 8 +- .../io/sentry/cache/tape/QueueFileTest.kt | 4 +- .../ClientReportMultiThreadingTest.kt | 10 +- .../sentry/clientreport/ClientReportTest.kt | 16 +- .../file/SentryFileInputStreamTest.kt | 2 +- .../debugmeta/ResourcesDebugMetaLoaderTest.kt | 22 +- .../modules/ManifestModulesLoaderTest.kt | 14 +- .../modules/ResourcesModulesLoaderTest.kt | 6 +- .../protocol/BreadcrumbSerializationTest.kt | 4 +- .../protocol/DebugMetaSerializationTest.kt | 2 +- .../java/io/sentry/protocol/DebugMetaTest.kt | 8 +- .../SentryExceptionSerializationTest.kt | 8 +- .../protocol/SentryLogsSerializationTest.kt | 4 +- .../SentryMetricsSerializationTest.kt | 4 +- .../SentryProfileSerializationTest.kt | 2 +- .../SentryStackTraceSerializationTest.kt | 2 +- .../protocol/SentryThreadSerializationTest.kt | 4 +- .../sentry/protocol/UserSerializationTest.kt | 4 +- .../ViewHierarchyNodeSerializationTest.kt | 2 +- ...ebInteractionMoveEventSerializationTest.kt | 2 +- .../RRWebOptionsEventSerializationTest.kt | 2 +- .../AsyncHttpTransportClientReportTest.kt | 10 +- .../transport/AsyncHttpTransportTest.kt | 2 +- .../transport/DistrustedCertificatesTest.kt | 2 +- .../io/sentry/transport/HttpConnectionTest.kt | 4 +- .../io/sentry/transport/RateLimiterTest.kt | 4 +- .../java/io/sentry/util/CheckInUtilsTest.kt | 24 +- .../java/io/sentry/util/CookieUtilsTest.kt | 54 +- .../test/java/io/sentry/util/HttpUtilsTest.kt | 8 +- .../test/java/io/sentry/util/InitUtilTest.kt | 2 +- .../sentry/util/JsonSerializationUtilsTest.kt | 2 +- .../test/java/io/sentry/util/LoadClassTest.kt | 4 +- .../io/sentry/util/MapObjectReaderTest.kt | 14 +- .../io/sentry/util/MapObjectWriterTest.kt | 2 +- .../io/sentry/util/MonitorConfigUtilsTest.kt | 16 +- .../test/java/io/sentry/util/SpanUtilsTest.kt | 2 +- .../java/io/sentry/util/TracingUtilsTest.kt | 10 +- .../test/java/io/sentry/util/UrlUtilsTest.kt | 6 +- 581 files changed, 4227 insertions(+), 4513 deletions(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 00630261065..7959ada57dc 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -46,7 +46,7 @@ agp = "9.5.1" sqlite = "2.6.2" sqliteRc = "2.8.0-alpha03" # Required by Room3 3.0.0-rc* slf4j = "1.7.30" -spotless = "8.8.0" +spotless = "8.11.0" springboot2 = "2.7.18" springboot3 = "3.5.0" springboot4 = "4.1.0" diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ActivityFramesTracker.java b/sentry-android-core/src/main/java/io/sentry/android/core/ActivityFramesTracker.java index 8aa737f7192..871021b4745 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ActivityFramesTracker.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ActivityFramesTracker.java @@ -231,16 +231,15 @@ private void runSafelyOnUiThread(final Runnable runnable, final String tag) { if (AndroidThreadChecker.getInstance().isMainThread()) { runnable.run(); } else { - handler.post( - () -> { - try { - runnable.run(); - } catch (Throwable ignored) { - if (tag != null) { - options.getLogger().log(SentryLevel.WARNING, "Failed to execute " + tag); - } - } - }); + handler.post(() -> { + try { + runnable.run(); + } catch (Throwable ignored) { + if (tag != null) { + options.getLogger().log(SentryLevel.WARNING, "Failed to execute " + tag); + } + } + }); } } catch (Throwable ignored) { if (tag != null) { 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 0c3b7d8d5ff..6d4a74429eb 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 @@ -228,23 +228,21 @@ private void startTracing(final @NotNull Activity activity) { transactionOptions.setTrimEnd(true); } transactionOptions.setWaitForChildren(true); - transactionOptions.setTransactionFinishedCallback( - (finishingTransaction) -> { - @Nullable Activity unwrappedActivity = weakActivity.get(); - if (unwrappedActivity != null) { - activityFramesTracker.setMetrics( - unwrappedActivity, finishingTransaction.getEventId()); - } else { - if (options != null) { - options - .getLogger() - .log( - SentryLevel.WARNING, - "Unable to track activity frames as the Activity %s has been destroyed.", - activityName); - } - } - }); + transactionOptions.setTransactionFinishedCallback(finishingTransaction -> { + @Nullable Activity unwrappedActivity = weakActivity.get(); + if (unwrappedActivity != null) { + activityFramesTracker.setMetrics(unwrappedActivity, finishingTransaction.getEventId()); + } else { + if (options != null) { + options + .getLogger() + .log( + SentryLevel.WARNING, + "Unable to track activity frames as the Activity %s has been destroyed.", + activityName); + } + } + }); // This will be the start timestamp of the transaction, as well as the ttid/ttfd spans final @NotNull SentryDate ttidStartTime; @@ -407,10 +405,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); } @@ -478,32 +475,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) { @@ -542,10 +537,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); + }); } } } @@ -1066,10 +1060,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 = 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 cb54723d8e1..622f74ca55a 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 @@ -379,23 +379,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-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 eb5a27c4a5e..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 @@ -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/ContextUtils.java b/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java index b71c3628c6e..3ee5d6d9f00 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 @@ -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. 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 7966ca98d99..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 @@ -49,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 3f042e08209..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 @@ -286,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/InternalSentrySdk.java b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java index 5400478cbfa..104d2f0c803 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 @@ -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. */ @@ -416,10 +412,9 @@ private static void deleteCurrentSessionFile( try { options .getExecutorService() - .submit( - () -> { - deleteCurrentSessionFile(options); - }); + .submit(() -> { + deleteCurrentSessionFile(options); + }); } catch (Throwable e) { options .getLogger() @@ -450,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 478d9ed624c..b981ce6eda1 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 @@ -66,15 +66,14 @@ private void startSession() { final long currentTimeMillis = currentDateProvider.getCurrentTimeMillis(); - scopes.configureScope( - scope -> { - if (lastUpdatedSession.get() == 0L) { - final @Nullable Session currentSession = scope.getSession(); - if (currentSession != null && currentSession.getStarted() != null) { - lastUpdatedSession.set(currentSession.getStarted().getTime()); - } - } - }); + scopes.configureScope(scope -> { + if (lastUpdatedSession.get() == 0L) { + final @Nullable Session currentSession = scope.getSession(); + if (currentSession != null && currentSession.getStarted() != null) { + lastUpdatedSession.set(currentSession.getStarted().getTime()); + } + } + }); final long lastUpdatedSession = this.lastUpdatedSession.get(); final boolean startNewSession = 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 e41bbbf28fb..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 @@ -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( 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 05352be394c..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) 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 7439de759d7..e3eb33af048 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 @@ -201,13 +201,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(); } 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 f97bbf2e72f..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(); + }); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackButton.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackButton.java index 22a010b07f9..c1d5a776449 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackButton.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackButton.java @@ -119,12 +119,11 @@ private void init( @Override public void setOnClickListener(final @Nullable OnClickListener listener) { delegate = listener; - super.setOnClickListener( - v -> { - new SentryUserFeedbackForm.Builder(getContext()).create().show(); - if (delegate != null) { - delegate.onClick(v); - } - }); + super.setOnClickListener(v -> { + new SentryUserFeedbackForm.Builder(getContext()).create().show(); + if (delegate != null) { + delegate.onClick(v); + } + }); } } 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 4be90baad56..23f59f8e282 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 @@ -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(); + } + }); } }; } @@ -252,33 +251,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); @@ -329,76 +327,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()); @@ -412,22 +408,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); } 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 index 133a1c6d8b5..b96eb5d97bd 100644 --- 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 @@ -234,28 +234,25 @@ private static void removeOnWebViewThread( 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); - } - }); + .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) { 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 2d20acbcf11..2a6d57872a4 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 @@ -42,22 +42,21 @@ public final class SpanFrameMetricsCollector // 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 82bd4ce9f72..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 @@ -137,53 +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); - 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(); - } - 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); + 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(); } + 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() 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 8fad115eed6..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 @@ -185,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/anr/AnrProfilingIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java index c101ef92adf..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 @@ -132,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"); } 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 13148097289..245950a17ee 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 @@ -266,7 +266,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/SentryGestureListener.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/SentryGestureListener.java index bb741d0cb2a..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 @@ -279,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; @@ -299,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; @@ -315,30 +313,28 @@ 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) { 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 ea94ea8e262..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 @@ -27,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/util/AndroidConnectionStatusProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java index df8a3b976dc..fe9acc69a23 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 @@ -629,15 +629,14 @@ private void unregisterNetworkCallback(final boolean clearObservers) { public void close() { closed = true; - submitSafe( - () -> { - unregisterNetworkCallback(/* clearObservers= */ true); - childCallbacks.clear(); - try (final @NotNull ISentryLifecycleToken ignored = connectivityManagerLock.acquire()) { - connectivityManager = null; - } - AppState.getInstance().removeAppStateListener(this); - }); + submitSafe(() -> { + unregisterNetworkCallback(/* clearObservers= */ true); + childCallbacks.clear(); + try (final @NotNull ISentryLifecycleToken ignored = connectivityManagerLock.acquire()) { + connectivityManager = null; + } + AppState.getInstance().removeAppStateListener(this); + }); } /** @@ -646,36 +645,35 @@ public void close() { */ @Override public void onForeground() { - 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; - } + 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; + } - // 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); - } + // 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 refresh the cache and notify observers 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(); + }); } /** @@ -684,16 +682,15 @@ public void onForeground() { */ @Override public void onBackground() { - 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); - }); + 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); + }); } /** 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 885ce5c2859..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 @@ -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/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 776d0103d2c..f7d3082bced 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 @@ -202,16 +202,15 @@ public final 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 697bf2a5a60..6425f78e767 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 @@ -132,29 +132,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) -> { @@ -361,19 +358,18 @@ public void stopCollection(final @Nullable String listenerId) { @SuppressLint("NewApi") 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") @@ -401,17 +397,16 @@ 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); + } + } + }); } } 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 3bb58e67048..509296a8463 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 @@ -558,24 +558,21 @@ private void scheduleHeadlessAppStartCheckOnMain() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Looper.getMainLooper() .getQueue() - .addIdleHandler( - () -> { - firstIdle = SystemClock.uptimeMillis(); - headlessAppStartCheckPending.set(false); - handleHeadlessAppStartIfNeededOnMain(); - return false; - }); - } else { - final Handler handler = new Handler(Looper.getMainLooper()); - handler.post( - () -> { + .addIdleHandler(() -> { firstIdle = SystemClock.uptimeMillis(); - handler.post( - () -> { - headlessAppStartCheckPending.set(false); - handleHeadlessAppStartIfNeededOnMain(); - }); + headlessAppStartCheckPending.set(false); + handleHeadlessAppStartIfNeededOnMain(); + return false; }); + } else { + final Handler handler = new Handler(Looper.getMainLooper()); + handler.post(() -> { + firstIdle = SystemClock.uptimeMillis(); + handler.post(() -> { + headlessAppStartCheckPending.set(false); + handleHeadlessAppStartIfNeededOnMain(); + }); + }); } } 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 1a88c1bec6d..bd406200408 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 @@ -273,7 +273,7 @@ class ActivityLifecycleIntegrationTest { contexts.any { it.operation == ActivityLifecycleIntegration.APP_START_COLD || it.operation == ActivityLifecycleIntegration.APP_START_WARM - } + }, ) } @@ -341,7 +341,7 @@ class ActivityLifecycleIntegrationTest { assertTrue( appStartTransaction.children.any { it.operation == ActivityLifecycleIntegration.APP_START_EXTENDED_OP - } + }, ) assertTrue(AppStartMetrics.getInstance().appStartExtension.isActive) assertNotNull(AppStartMetrics.getInstance().appStartExtension.extendedAppStartSpan) @@ -473,7 +473,7 @@ class ActivityLifecycleIntegrationTest { assertTrue( transaction.children.any { it.operation == ActivityLifecycleIntegration.APP_START_EXTENDED_OP - } + }, ) assertFalse(transaction.isFinished) @@ -919,7 +919,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() @@ -990,7 +990,7 @@ class ActivityLifecycleIntegrationTest { initializer = { it.tracesSampleRate = 1.0 it.isEnableActivityLifecycleTracingAutoFinish = false - } + }, ) sut.register(fixture.scopes, fixture.options) val activity = mock() @@ -1473,7 +1473,7 @@ class ActivityLifecycleIntegrationTest { uiLoadTransaction.children.any { it.operation == ActivityLifecycleIntegration.APP_START_COLD || it.operation == ActivityLifecycleIntegration.APP_START_WARM - } + }, ) sut.onActivityPostCreated(activity, fixture.bundle) @@ -1678,7 +1678,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 @@ -1707,7 +1707,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 a13f3fe1246..5a27a303342 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 @@ -215,7 +215,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/AndroidOptionsInitializerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt index 5b1c25d82ef..226ea753977 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 @@ -279,8 +279,8 @@ class AndroidOptionsInitializerTest { assertTrue( fixture.sentryOptions.cacheDirPath?.endsWith( - "${File.separator}cache${File.separator}sentry" - )!! + "${File.separator}cache${File.separator}sentry", + )!!, ) } @@ -290,7 +290,7 @@ class AndroidOptionsInitializerTest { assertTrue( AndroidOptionsInitializer.getCacheDir(fixture.context) .path - .endsWith("${File.separator}cache${File.separator}sentry") + .endsWith("${File.separator}cache${File.separator}sentry"), ) } @@ -300,8 +300,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()) } @@ -312,8 +312,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", + )!!, ) } @@ -407,7 +407,7 @@ class AndroidOptionsInitializerTest { configureOptions = { dsn = SAAS_DSN this.sslSocketFactory = sslSocketFactory - } + }, ) assertEquals(sslSocketFactory, fixture.sentryOptions.sslSocketFactory) @@ -438,7 +438,7 @@ class AndroidOptionsInitializerTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("PerfettoContinuousProfiling") + .contains("PerfettoContinuousProfiling"), ) } @@ -451,7 +451,7 @@ class AndroidOptionsInitializerTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("PerfettoContinuousProfiling") + .contains("PerfettoContinuousProfiling"), ) } @@ -502,7 +502,7 @@ class AndroidOptionsInitializerTest { configureOptions = { profilesSampleRate = 1.0 isEnableLegacyProfiling = false - } + }, ) assertEquals(NoOpTransactionProfiler.getInstance(), fixture.sentryOptions.transactionProfiler) @@ -515,7 +515,7 @@ class AndroidOptionsInitializerTest { configureOptions = { profilesSampler = mock() isEnableLegacyProfiling = false - } + }, ) assertEquals(NoOpTransactionProfiler.getInstance(), fixture.sentryOptions.transactionProfiler) @@ -530,7 +530,7 @@ class AndroidOptionsInitializerTest { configureOptions = { profilesSampleRate = 1.0 isEnableLegacyProfiling = false - } + }, ) assertEquals(NoOpTransactionProfiler.getInstance(), fixture.sentryOptions.transactionProfiler) @@ -638,7 +638,7 @@ 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 } @@ -818,7 +818,7 @@ class AndroidOptionsInitializerTest { assertFalse( (activityLifeCycleIntegration as ActivityLifecycleIntegration) .activityFramesTracker - .isFrameMetricsAggregatorAvailable + .isFrameMetricsAggregatorAvailable, ) } @@ -839,7 +839,7 @@ class AndroidOptionsInitializerTest { assertTrue( (activityLifeCycleIntegration as ActivityLifecycleIntegration) .activityFramesTracker - .isFrameMetricsAggregatorAvailable + .isFrameMetricsAggregatorAvailable, ) } @@ -857,7 +857,7 @@ class AndroidOptionsInitializerTest { assertFalse( (activityLifeCycleIntegration as ActivityLifecycleIntegration) .activityFramesTracker - .isFrameMetricsAggregatorAvailable + .isFrameMetricsAggregatorAvailable, ) } @@ -876,7 +876,7 @@ class AndroidOptionsInitializerTest { assertFalse( (activityLifeCycleIntegration as ActivityLifecycleIntegration) .activityFramesTracker - .isFrameMetricsAggregatorAvailable + .isFrameMetricsAggregatorAvailable, ) } @@ -898,7 +898,7 @@ class AndroidOptionsInitializerTest { assertTrue( (activityLifeCycleIntegration as ActivityLifecycleIntegration) .activityFramesTracker - .isFrameMetricsAggregatorAvailable + .isFrameMetricsAggregatorAvailable, ) } @@ -954,7 +954,7 @@ class AndroidOptionsInitializerTest { listOf( AndroidOptionsInitializer.COMPOSE_CLASS_NAME, AndroidOptionsInitializer.SENTRY_COMPOSE_GESTURE_INTEGRATION_CLASS_NAME, - ) + ), ) assertTrue { fixture.sentryOptions.gestureTargetLocators.size == 2 } @@ -981,7 +981,7 @@ class AndroidOptionsInitializerTest { fixture.initSut() assertIs( - fixture.sentryOptions.compositePerformanceCollector + fixture.sentryOptions.compositePerformanceCollector, ) } @@ -1118,7 +1118,7 @@ class AndroidOptionsInitializerTest { AndroidOptionsInitializer.getCacheDir(fixture.context), PersistingScopeObserver.SCOPE_CACHE, ) - .exists() + .exists(), ) } @@ -1134,7 +1134,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 f402af24f80..8f493343d1e 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 @@ -153,12 +153,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 cac76c024af..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 @@ -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 3de3e054630..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 @@ -403,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 5f14e029d0e..1bafcdfdbde 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 @@ -154,7 +154,7 @@ class LifecycleWatcherTest { assertEquals("navigation", it.type) assertEquals(SentryLevel.INFO, it.level) // cant assert data, its not a public API - } + }, ) } @@ -177,7 +177,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 9ae1a9b023d..a6a3f1f34fd 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 @@ -1197,7 +1197,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) @@ -1738,7 +1739,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) @@ -2041,13 +2042,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, + ), ) } @@ -2062,13 +2063,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, + ), ) } @@ -2144,7 +2145,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) @@ -2175,7 +2176,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) @@ -2799,7 +2800,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) @@ -2819,7 +2820,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/NetworkBreadcrumbsIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/NetworkBreadcrumbsIntegrationTest.kt index 711f5f7fe0b..4ed43a40c3b 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 @@ -132,7 +132,7 @@ class NetworkBreadcrumbsIntegrationTest { assertEquals("network.event", it.category) assertEquals(SentryLevel.INFO, it.level) assertEquals("NETWORK_AVAILABLE", it.data["action"]) - } + }, ) } @@ -154,7 +154,7 @@ class NetworkBreadcrumbsIntegrationTest { assertEquals("network.event", it.category) assertEquals(SentryLevel.INFO, it.level) assertEquals("NETWORK_LOST", it.data["action"]) - } + }, ) } @@ -448,7 +448,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 0ab922fc32a..c6b4b73fa78 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 @@ -288,7 +288,7 @@ class PerformanceAndroidEventProcessorTest { emptyMap(), emptyMap(), null, - ) + ), ) tr.spans.add( SentrySpan( @@ -304,7 +304,7 @@ class PerformanceAndroidEventProcessorTest { emptyMap(), emptyMap(), null, - ) + ), ) tr.spans.add( SentrySpan( @@ -320,7 +320,7 @@ class PerformanceAndroidEventProcessorTest { emptyMap(), emptyMap(), null, - ) + ), ) tr = sut.process(tr, Hint()) @@ -590,7 +590,7 @@ class PerformanceAndroidEventProcessorTest { val metrics = mapOf( MeasurementValue.KEY_FRAMES_TOTAL to - MeasurementValue(1f, MeasurementUnit.Duration.MILLISECOND.apiName()) + MeasurementValue(1f, MeasurementUnit.Duration.MILLISECOND.apiName()), ) whenever(fixture.activityFramesTracker.takeMetrics(any())).thenReturn(metrics) @@ -643,7 +643,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 }) @@ -744,7 +744,7 @@ class PerformanceAndroidEventProcessorTest { "contentprovider.load" == it.op || "application.load" == it.op || "activity.load" == it.op - } + }, ) } @@ -795,7 +795,7 @@ class PerformanceAndroidEventProcessorTest { "contentprovider.load" == it.op || "application.load" == it.op || "activity.load" == it.op - } + }, ) } @@ -1266,7 +1266,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)) @@ -1275,7 +1275,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 b27df5f6bf1..e33a62b08bf 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 @@ -596,7 +596,7 @@ private class EllipsizedTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) // Ellipsize middle @@ -612,7 +612,7 @@ private class EllipsizedTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) // Ellipsize start @@ -628,7 +628,7 @@ private class EllipsizedTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) // Non-ellipsized text for comparison @@ -642,7 +642,7 @@ private class EllipsizedTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) setContentView(linearLayout) @@ -779,7 +779,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) @@ -794,7 +794,7 @@ private class MultiLineTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) // Short single-line text for comparison @@ -808,7 +808,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 32b38764626..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 @@ -63,7 +63,7 @@ class SendCachedEnvelopeIntegrationTest { sender } else { null - } + }, ) return SendCachedEnvelopeIntegration(factory, LazyEvaluator { hasStartupCrashMarker }) 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 a223358c1d1..0934ab97a5f 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 @@ -33,13 +33,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 - } + }, ) } @@ -179,7 +179,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, 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 36a23bf3688..2717128af95 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 @@ -163,7 +163,7 @@ class SentryAndroidTest { (no managed stack frames) """ .trimIndent() - .byteInputStream() + .byteInputStream(), ) } shadowActivityManager.addApplicationExitInfo(exitInfo) @@ -251,7 +251,7 @@ class SentryAndroidTest { SystemEventsBreadcrumbsIntegration( ApplicationProvider.getApplicationContext(), CustomHandler(Looper.getMainLooper()), - ) + ), ) refOptions = it } @@ -454,7 +454,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) 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 ad6d29b5614..9cb941e4b1d 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 @@ -41,10 +41,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 19414515b87..c95ab14e743 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 @@ -330,7 +330,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.", ), ) } @@ -472,7 +472,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 index f6bb1747426..96f8e060f00 100644 --- 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 @@ -275,7 +275,7 @@ class SentryWebViewTracingTest { listOf("example.com"), Sentry.getCurrentScopes(), installer, - ) + ), ) .isTrue() shadowOf(Looper.getMainLooper()).idle() @@ -320,7 +320,7 @@ class SentryWebViewTracingTest { loadClass.isClassAvailable( eq(SentryWebViewTracing.SCRIPT_HANDLER_CLASS_NAME), any(), - ) + ), ) .thenReturn(false) @@ -330,7 +330,7 @@ class SentryWebViewTracingTest { listOf("example.com"), scopes, loadClass, - ) + ), ) .isFalse() // The adoption marker is registered on use, even when nothing can be installed. 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 d5932b75b90..f49c5d02c18 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 @@ -61,7 +61,7 @@ class SpanFrameMetricsCollectorTest { SentryNanotimeDate(System.currentTimeMillis(), endTimeStampNanos) } else { null - } + }, ) return span } @@ -81,7 +81,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 60282aca26d..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 @@ -389,7 +389,7 @@ class SystemEventsBreadcrumbsIntegrationTest { assertTrue( AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration - } + }, ) } @@ -403,7 +403,7 @@ class SystemEventsBreadcrumbsIntegrationTest { assertFalse( AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration - } + }, ) } @@ -416,7 +416,7 @@ class SystemEventsBreadcrumbsIntegrationTest { assertTrue( AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration - } + }, ) sut.close() @@ -424,7 +424,7 @@ class SystemEventsBreadcrumbsIntegrationTest { assertFalse( 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() @@ -449,7 +449,7 @@ class SystemEventsBreadcrumbsIntegrationTest { assertFalse( 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 ca4c51319aa..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 @@ -58,8 +58,8 @@ class TombstoneIntegrationTest : ApplicationExitIntegrationTestBase(), - ) + ), ) .thenReturn(isLifecycleAvailable) whenever(scopes.options).thenReturn(options) @@ -109,7 +109,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 index 210bdf80dad..ce7d3f02bc4 100644 --- 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 @@ -84,7 +84,7 @@ class WebViewTracePropagationScriptTest { "pwned", 1, null, - ) + ), ) return Result(metas, pwned) } finally { @@ -220,7 +220,7 @@ class WebViewTracePropagationScriptTest { fun `normalizeHosts drops blank entries and duplicates`() { val hosts = WebViewTracePropagationScript.normalizeHosts( - listOf(" ", "", "example.com", "https://EXAMPLE.com/", "other.com") + listOf(" ", "", "example.com", "https://EXAMPLE.com/", "other.com"), ) assertThat(hosts).containsExactly("example.com", "other.com").inOrder() @@ -250,7 +250,7 @@ class WebViewTracePropagationScriptTest { 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") + listOf("example.com:8443", "https://other.com:443/x", "[::1]:8080", "10.0.2.2:3000"), ) assertThat(rules) @@ -280,7 +280,7 @@ class WebViewTracePropagationScriptTest { assertThat(WebViewTracePropagationScript.stripTransactionFromBaggage(baggage)) .isEqualTo( "sentry-trace_id=d4cda95b652f4a1592b449d5929fda1b,sentry-environment=prod," + - "sentry-sample_rate=1.0,othervendor=keepme" + "sentry-sample_rate=1.0,othervendor=keepme", ) } @@ -288,8 +288,8 @@ class WebViewTracePropagationScriptTest { fun `stripTransactionFromBaggage returns null when only sentry-transaction is left`() { assertThat( WebViewTracePropagationScript.stripTransactionFromBaggage( - "sentry-transaction=GET%20%2Fusers%2F123" - ) + "sentry-transaction=GET%20%2Fusers%2F123", + ), ) .isNull() assertThat(WebViewTracePropagationScript.stripTransactionFromBaggage(null)).isNull() 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 47163c0e841..d6e37383dea 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 @@ -168,7 +168,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) @@ -181,7 +181,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) @@ -227,7 +227,7 @@ class AndroidEnvelopeCacheTest { val hints = HintUtils.createWithTypeCheckHint( - MemoryLimiterHint(0, NoOpLogger.getInstance(), 23456789L, false) + MemoryLimiterHint(0, NoOpLogger.getInstance(), 23456789L, false), ) cache.storeEnvelope(fixture.envelope, hints) @@ -247,7 +247,7 @@ class AndroidEnvelopeCacheTest { cache.storeEnvelope( envelope, HintUtils.createWithTypeCheckHint( - MemoryLimiterHint(0, NoOpLogger.getInstance(), exitTimestamp, true) + MemoryLimiterHint(0, NoOpLogger.getInstance(), exitTimestamp, true), ), ) @@ -270,7 +270,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), ), ) @@ -287,13 +287,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 index ed37286026f..bce34be5e27 100644 --- 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 @@ -432,7 +432,7 @@ class AndroidConnectionStatusProviderConcurrencyTest { override fun onAvailable(network: Network) { stall.block(Unit) } - } + }, ) val notification = fixture.startOnCallerThread { networkCallback.onAvailable(fixture.network) } stall.awaitEntered() @@ -464,7 +464,7 @@ class AndroidConnectionStatusProviderConcurrencyTest { override fun onAvailable(network: Network) { stall.block(Unit) } - } + }, ) val childNetworkCallback = mock() fixture.addChildNetworkCallback(childNetworkCallback) @@ -491,7 +491,7 @@ class AndroidConnectionStatusProviderConcurrencyTest { override fun onAvailable(network: Network) { AndroidConnectionStatusProvider.removeNetworkCallback(this) } - } + }, ) val otherChildNetworkCallback = mock() fixture.addChildNetworkCallback(otherChildNetworkCallback) 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 b0fa556deae..38a3365ba8e 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 @@ -80,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) @@ -187,7 +187,7 @@ class AndroidConnectionStatusProviderTest { eq(Manifest.permission.ACCESS_NETWORK_STATE), any(), any(), - ) + ), ) .thenReturn(PERMISSION_GRANTED) @@ -266,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) @@ -305,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) @@ -354,7 +354,7 @@ class AndroidConnectionStatusProviderTest { buildInfo, null, mock(), - ) + ), ) } @@ -384,7 +384,7 @@ class AndroidConnectionStatusProviderTest { @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()) + contextMock.checkPermission(eq(Manifest.permission.ACCESS_NETWORK_STATE), any(), any()), ) .thenReturn(PERMISSION_DENIED) val provider = AndroidConnectionStatusProvider(contextMock, options, buildInfo, ticker) @@ -838,7 +838,7 @@ class AndroidConnectionStatusProviderTest { assertFalse( 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 64d2b3dc281..52cd7e6d3c3 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 @@ -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/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/ScreenshotUtilsMaskedScreenshotTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/ScreenshotUtilsMaskedScreenshotTest.kt index 9bc6f9f85b0..cea4a6d5bbf 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 @@ -135,7 +135,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 a036583adb8..c4401d74c6c 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 @@ -164,7 +164,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 c6e4bf44cbb..91a1e4afe3a 100644 --- a/sentry-android-distribution/build.gradle.kts +++ b/sentry-android-distribution/build.gradle.kts @@ -45,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/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 1b98cd59c7b..195b388faf0 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 @@ -78,7 +78,7 @@ class MainActivity : ComponentActivity() { .trimIndent() file.writeText(corruptedEnvelopeContent) println("Wrote corrupted envelope to: ${file.absolutePath}") - } + }, ) { Text("Write Corrupted Envelope") } @@ -90,7 +90,7 @@ class MainActivity : ComponentActivity() { } else { postNotification() } - } + }, ) { Text("Trigger Notification") } @@ -101,11 +101,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/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 49bfb3fb09f..b986c2c1881 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 @@ -71,9 +71,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() @@ -112,9 +112,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 6bbbe95253a..b33f70830c6 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 @@ -428,7 +428,7 @@ class UserFeedbackUiTest : BaseUiTest() { name = "Test User" username = "Test UserName" email = "Test User Email" - } + }, ) showDialogAndCheck { // Name and email are filled with Sentry user properties @@ -452,7 +452,7 @@ class UserFeedbackUiTest : BaseUiTest() { name = "Test User" username = "Test UserName" email = "Test User Email" - } + }, ) showDialogAndCheck { // Name and email are not filled @@ -490,9 +490,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!! @@ -560,15 +560,17 @@ class UserFeedbackUiTest : BaseUiTest() { @Test fun userFeedbackWidgetDefaultsOverridden() { initSentry() - showWidgetAndCheck({ widget -> - widget.compoundDrawablePadding = 1 - widget.setCompoundDrawables(null, null, null, null) - widget.isAllCaps = true - widget.setBackgroundResource(R.drawable.sentry_edit_text_border) - widget.setTextColor(Color.RED) - widget.text = "My custom text" - widget.setPadding(0, 0, 0, 0) - }) { widget -> + showWidgetAndCheck( + { widget -> + widget.compoundDrawablePadding = 1 + widget.setCompoundDrawables(null, null, null, null) + widget.isAllCaps = true + widget.setBackgroundResource(R.drawable.sentry_edit_text_border) + widget.setTextColor(Color.RED) + widget.text = "My custom text" + widget.setPadding(0, 0, 0, 0) + }, + ) { widget -> val densityScale = context.resources.displayMetrics.density assertEquals(1, widget.compoundDrawablePadding) 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/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/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 fdfeb61e05f..849605d5095 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 @@ -53,7 +53,7 @@ class ProfilingSampleActivity : AppCompatActivity() { scrollingIdlingResource.decrement() } } - } + }, ) } } 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/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 d7d8895c608..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 @@ -209,7 +209,7 @@ class BackStackObserverTest { else -> emptyMap() }, ) - } + }, ) sut.onBackStackChanged(listOf(HomeScreen(), previousProfile)) @@ -269,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"))) @@ -306,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")) @@ -331,7 +331,7 @@ class BackStackObserverTest { mapOf("entry" to "/ProfileScreen"), mapOf("entry" to "/SettingsScreen"), mapOf("entry" to "/HomeScreen"), - ) + ), ) } @@ -362,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, @@ -450,7 +450,7 @@ class BackStackObserverTest { else -> emptyMap() }, ) - } + }, ) sut.onBackStackChanged(listOf(home, profile)) @@ -491,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) } @@ -506,7 +506,7 @@ class BackStackObserverTest { fixture.scopes.startTransaction( any(), transactionOptionsCaptor.capture(), - ) + ), ) .thenAnswer { val transactionContext = it.arguments[0] as TransactionContext @@ -656,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 @@ -693,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 @@ -729,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 @@ -764,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 2b8547b4084..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 @@ -89,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") } @@ -283,8 +283,8 @@ class CoordinatedBackStackObserverTest { listOf( mapOf("entry" to "/PageA", "entry_arguments" to mapOf("page" to "PageA")), mapOf("entry" to "/Home", "entry_arguments" to mapOf("page" to "Home")), - ) - ) + ), + ), ) } @@ -311,7 +311,7 @@ class CoordinatedBackStackObserverTest { 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"))) + mapOf("Back Stack" to listOf(mapOf("entry" to "/PageA"), mapOf("entry" to "/Settings"))), ) } @@ -437,7 +437,7 @@ class CoordinatedBackStackObserverTest { tracesSampleRate = 1.0 idleTimeout = null deadlineTimeout = 0 - } + }, ) val coordinator = NavLeaseCoordinator() val startedTransactions = mutableListOf() @@ -480,7 +480,7 @@ class CoordinatedBackStackObserverTest { scopes, NavRootInfo(otherLifecycle, activity = null), NoOpNavStatePublisher, - ) + ), ) other.onBackStackUpdate() otherLifecycle.currentState = Lifecycle.State.STARTED 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 145b5c0cf74..dc50114f250 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 @@ -1461,7 +1461,7 @@ class SentryNavEffectLifecycleIntegrationTest { * transaction holds the scope's transaction slot. */ fun returnToHomeWhileCheckoutUiLoadIsUnfinished( - finishHomeTransaction: Boolean = true + finishHomeTransaction: Boolean = true, ): Pair, ActivityController> { installActivityLifecycleIntegration(CheckoutActivity::class.java) val home = Robolectric.buildActivity(HomeActivity::class.java).setup() @@ -1545,7 +1545,7 @@ class SentryNavEffectLifecycleIntegrationTest { ) .forEach { activityClass: Class -> packageManager.addActivityIfNotPresent( - ComponentName(application.packageName, activityClass.name) + ComponentName(application.packageName, activityClass.name), ) } return Fixture(tracesSampleRate).also { current = it } 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 7a0ed005f8e..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 @@ -64,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), ) } } @@ -259,7 +259,7 @@ class SentryNavEffectTest { mapOf("entry" to "/ProfileRoute"), mapOf("entry" to "/HomeRoute"), mapOf("entry" to "/HomeRoute"), - ) + ), ) } @@ -361,7 +361,7 @@ class SentryNavEffectTest { mutableStateOf>( BackStackEntryMapper { entry -> SentryBackStackEntry(entry::class.simpleName ?: "") - } + }, ) composeRule.setContent { @@ -399,7 +399,7 @@ class SentryNavEffectTest { mutableStateOf>( BackStackEntryMapper { entry -> SentryBackStackEntry(entry::class.simpleName ?: "unknown") - } + }, ) composeRule.setContent { @@ -468,7 +468,7 @@ class SentryNavEffectTest { listOf( mapOf("entry" to "/ProfileRoute", "entry_arguments" to mapOf("userId" to "123")), mapOf("entry" to "/HomeRoute"), - ) + ), ) } 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 5f8b0ccd003..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 @@ -330,7 +330,7 @@ class NavScopeTest { override fun setTransaction(transaction: String?) { throw ThrowingScopeObserverException() } - } + }, ) assertThrows(ThrowingScopeObserverException::class.java) { @@ -442,7 +442,7 @@ class NavScopeTest { private fun resumedNavScopes(): NavScopes = NavScopes(scopes, coordinator).also { it.attach( - NavRootInfo(TestLifecycleOwner().also(lifecycleOwners::add).lifecycle, activity = null) + NavRootInfo(TestLifecycleOwner().also(lifecycleOwners::add).lifecycle, activity = null), ) } 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 fb9782877e2..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 @@ -40,7 +40,7 @@ class NavScopesIntegrationTest { NavTransactionRequest( name = "/Checkout", newOptions = ::TransactionOptions, - ) + ), ) } assertThat(contextsAtSampling).isEmpty() 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 84e1d1822c9..be5e1141210 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 @@ -187,7 +187,7 @@ class NavScopesTest { override fun setContexts(contexts: Contexts) { throw failure } - } + }, ) val thrown = assertThrows(IllegalStateException::class.java) { fixture.incoming.dispose() } @@ -393,7 +393,7 @@ class NavScopesTest { override fun setTransaction(transaction: String?) { if (transaction == "/Home") screensAtBinding += fixture.scope.screen } - } + }, ) fixture.incoming.dispose() @@ -540,7 +540,7 @@ class NavScopesTest { val fixture = Fixture.create() val covered = fixture.coveredNavScopes() covered.startNavTransaction( - navTransactionRequest("/Result", data = mapOf("arguments" to "id=1")) + navTransactionRequest("/Result", data = mapOf("arguments" to "id=1")), ) fixture.incoming.dispose() @@ -721,7 +721,7 @@ class NavScopesTest { override fun setContexts(contexts: Contexts) { if (observerThrows) throw failure } - } + }, ) val thrown = assertThrows(IllegalStateException::class.java) { fixture.incoming.dispose() } assertThat(thrown).isSameInstanceAs(failure) @@ -806,7 +806,7 @@ class NavScopesTest { SentryOptions().apply { setLogger(this@Fixture.logger) isDebug = true - } + }, ) doAnswer { if (isEnabled) { 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 82c45a1df90..a1363ffdc25 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 @@ -318,7 +318,7 @@ class StagedNavTransactionTest { whenever(finished.isFinished).thenReturn(true) stagedNavTransaction.updateRequest( - navTransactionRequest("/Profile", contexts = updatedContexts) + navTransactionRequest("/Profile", contexts = updatedContexts), ) stagedNavTransaction.publishTo(fixture.scope) @@ -332,7 +332,7 @@ class StagedNavTransactionTest { stagedNavTransaction.stage(request) stagedNavTransaction.updateRequest( - navTransactionRequest("/Profile", contexts = updatedContexts) + navTransactionRequest("/Profile", contexts = updatedContexts), ) stagedNavTransaction.publishTo(fixture.scope) @@ -348,7 +348,7 @@ class StagedNavTransactionTest { val started = fixture.start() stagedNavTransaction.updateRequest( - navTransactionRequest("/Profile", contexts = updatedContexts) + navTransactionRequest("/Profile", contexts = updatedContexts), ) stagedNavTransaction.publishTo(fixture.scope) @@ -365,7 +365,7 @@ class StagedNavTransactionTest { stagedNavTransaction.finish(fixture.scope) stagedNavTransaction.updateRequest( - navTransactionRequest("/Profile", contexts = updatedContexts) + navTransactionRequest("/Profile", contexts = updatedContexts), ) stagedNavTransaction.publishTo(fixture.scope) @@ -898,7 +898,7 @@ class StagedNavTransactionTest { SentryOptions().apply { setLogger(this@Fixture.logger) isDebug = true - } + }, ) whenever(scopes.startTransaction(any(), any())) .thenAnswer { @@ -923,7 +923,7 @@ class StagedNavTransactionTest { throw ThrowingScopeObserverException() } } - } + }, ) } diff --git a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt index 96a68c1960f..61d56f4236b 100644 --- a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt +++ b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt @@ -38,10 +38,12 @@ class NativeBackendTest { @Test fun `propagates app hang tracking options`() { - initialize({ - isEnableNdkAppHangTracking = true - ndkAppHangTimeoutIntervalMillis = 2000 - }) { + initialize( + { + isEnableNdkAppHangTracking = true + ndkAppHangTimeoutIntervalMillis = 2000 + }, + ) { assertThat(it.isEnableAppHangTracking).isTrue() assertThat(it.appHangTimeoutMillis).isEqualTo(2000L) } diff --git a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt index b8bf6f31e29..15f47d70780 100644 --- a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt +++ b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt @@ -380,7 +380,7 @@ class SentryNdkCrashServiceTest { .setReason(reason) .setTimestamp(timestamp) .setTraceInputStream(trace) - .build() + .build(), ) } 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/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 943e4fb6df7..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 @@ -13,7 +13,7 @@ class SentryNdkUtilTest { assertTrue( options.sdkVersion!!.packageSet.any { it.name == "maven:io.sentry:sentry-android-ndk" && it.version == BuildConfig.VERSION_NAME - } + }, ) } 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 bebaf95d396..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 @@ -267,7 +267,7 @@ public class ReplayIntegration( lifecycleState = STARTED, replayId = replayId ?: SentryId.EMPTY_ID, captureStrategy = strategy, - ) + ), ) registerRootViewListeners() @@ -370,7 +370,7 @@ public class ReplayIntegration( current.copy( replayId = replayId ?: SentryId.EMPTY_ID, captureStrategy = activeStrategy, - ) + ), ) } @@ -470,7 +470,7 @@ public class ReplayIntegration( lifecycleState = STOPPED, replayId = SentryId.EMPTY_ID, captureStrategy = null, - ) + ), ) } @@ -728,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 91a849627ea..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 @@ -114,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, @@ -137,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 -> { @@ -151,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 6956782cc27..e6019486fba 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 @@ -188,7 +188,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 06be58e19de..49ec7931ff1 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() @@ -344,7 +344,7 @@ internal class PixelCopyStrategy( } finally { finishFrame() } - } + }, ) if (submitted == null) { recycleCaptures(captures) @@ -386,7 +386,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 8e08b936bd5..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 @@ -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 49ec8565c1b..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 @@ -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(), ) } 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 9e8c65bc75a..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 @@ -31,7 +31,7 @@ class ReplayGestureConverterTest { } fun getSut( - dateProvider: ICurrentDateProvider = ICurrentDateProvider { now } + dateProvider: ICurrentDateProvider = ICurrentDateProvider { now }, ): ReplayGestureConverter = ReplayGestureConverter(dateProvider, ticker) } 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/test/java/io/sentry/android/timber/SentryTimberIntegrationTest.kt b/sentry-android-timber/src/test/java/io/sentry/android/timber/SentryTimberIntegrationTest.kt index 758e6568c10..696a8ccb806 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 @@ -110,7 +110,7 @@ class SentryTimberIntegrationTest { assertTrue( fixture.options.sdkVersion!!.packageSet.any { it.name == "maven:io.sentry:sentry-android-timber" && it.version == BuildConfig.VERSION_NAME - } + }, ) } @@ -147,7 +147,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 3fd80e495fd..bdc71ea3136 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 @@ -191,7 +191,7 @@ class SentryTimberTreeTest { check { assertEquals("tag", it.getTag("TimberTag")) assertEquals(sentryLevel, it.level) - } + }, ) } } @@ -210,7 +210,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) } }, ) } @@ -226,7 +226,7 @@ class SentryTimberTreeTest { assertEquals("test count: 32", message.formatted) assertEquals("32", message.params!!.first()) } - } + }, ) } @@ -270,7 +270,7 @@ class SentryTimberTreeTest { assertEquals("Timber", it.category) assertEquals(SentryLevel.INFO, it.level) assertEquals("message", it.message) - } + }, ) } @@ -284,7 +284,7 @@ class SentryTimberTreeTest { assertEquals("exception", it.category) assertEquals(SentryLevel.ERROR, it.level) assertEquals("test", it.message) - } + }, ) } diff --git a/sentry-apache-http-client-5/src/test/kotlin/io/sentry/transport/apache/ApacheHttpClientTransportClientReportTest.kt b/sentry-apache-http-client-5/src/test/kotlin/io/sentry/transport/apache/ApacheHttpClientTransportClientReportTest.kt index afe0b38538d..128bf8e4100 100644 --- a/sentry-apache-http-client-5/src/test/kotlin/io/sentry/transport/apache/ApacheHttpClientTransportClientReportTest.kt +++ b/sentry-apache-http-client-5/src/test/kotlin/io/sentry/transport/apache/ApacheHttpClientTransportClientReportTest.kt @@ -60,7 +60,7 @@ class ApacheHttpClientTransportClientReportTest { envelopeAfterClientReportAttached = SentryEnvelope.from(options.serializer, SentryEvent(), null) whenever( - clientReportRecorder.attachReportToEnvelope(same(envelopeBeforeClientReportAttached)) + clientReportRecorder.attachReportToEnvelope(same(envelopeBeforeClientReportAttached)), ) .thenReturn(envelopeAfterClientReportAttached) } diff --git a/sentry-apache-http-client-5/src/test/kotlin/io/sentry/transport/apache/ApacheHttpClientTransportFactoryTest.kt b/sentry-apache-http-client-5/src/test/kotlin/io/sentry/transport/apache/ApacheHttpClientTransportFactoryTest.kt index 80dc653fa45..1bfb6519659 100644 --- a/sentry-apache-http-client-5/src/test/kotlin/io/sentry/transport/apache/ApacheHttpClientTransportFactoryTest.kt +++ b/sentry-apache-http-client-5/src/test/kotlin/io/sentry/transport/apache/ApacheHttpClientTransportFactoryTest.kt @@ -29,7 +29,7 @@ class ApacheHttpClientTransportFactoryTest { SentryOptions().apply { this.connectionTimeoutMillis = 1500 this.readTimeoutMillis = 2500 - } + }, ) val requestConfig = transport.getClient().getRequestConfig() assertEquals(1500, requestConfig.connectTimeout.toMilliseconds()) 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 e53da365d56..07e36ea4b5c 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 @@ -112,7 +112,7 @@ class SentryApollo3InterceptorTest { MockResponse() .setBody(responseBody) .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) if (beforeSpan != null) { @@ -273,8 +273,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")) @@ -365,8 +365,8 @@ class SentryApollo3InterceptorTest { beforeSpan = { span, request, response -> span.description = "overwritten description" span - } - ) + }, + ), ) verify(fixture.scopes) @@ -411,7 +411,7 @@ class SentryApollo3InterceptorTest { beforeSpan = { span, _, _ -> span.spanContext.sampled = false error("callback failed") - } + }, ) assertThat(sut.query(LaunchDetailsQuery("83")).execute().data).isNotNull() @@ -438,7 +438,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 756f0d9c26b..c31a83db0b8 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 @@ -75,7 +75,7 @@ class SentryApollo4HttpInterceptorTestWithV3Implementation : abstract class SentryApollo4HttpInterceptorTest( private val executeQueryImplementation: - KSuspendFunction1, ApolloResponse> + KSuspendFunction1, ApolloResponse>, ) { class Fixture { val server = MockWebServer() @@ -126,7 +126,7 @@ abstract class SentryApollo4HttpInterceptorTest( MockResponse() .setBody(responseBody) .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) if (beforeSpan != null) { @@ -287,8 +287,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")) @@ -379,8 +379,8 @@ abstract class SentryApollo4HttpInterceptorTest( beforeSpan = { span, request, response -> span.description = "overwritten description" span - } - ) + }, + ), ) verify(fixture.scopes) @@ -425,7 +425,7 @@ abstract class SentryApollo4HttpInterceptorTest( beforeSpan = { span, _, _ -> span.spanContext.sampled = false error("callback failed") - } + }, ) assertThat(executeQueryImplementation(sut.query(LaunchDetailsQuery("83"))).data).isNotNull() @@ -452,7 +452,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 f74d0fec111..7333ef04bcf 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 @@ -135,7 +135,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 acd27f0ee1b..f0e17bef225 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 @@ -72,7 +72,7 @@ class SentryApollo5HttpInterceptorTestWithV5Implementation : abstract class SentryApollo5HttpInterceptorTest( private val executeQueryImplementation: - KSuspendFunction1, ApolloResponse> + KSuspendFunction1, ApolloResponse>, ) { class Fixture { val server = MockWebServer() @@ -123,7 +123,7 @@ abstract class SentryApollo5HttpInterceptorTest( MockResponse() .setBody(responseBody) .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) if (beforeSpan != null) { @@ -383,8 +383,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")) @@ -398,8 +398,8 @@ abstract class SentryApollo5HttpInterceptorTest( beforeSpan = { span, request, response -> span.description = "overwritten description" span - } - ) + }, + ), ) verify(fixture.scopes) @@ -441,7 +441,7 @@ abstract class SentryApollo5HttpInterceptorTest( beforeSpan = { span, _, _ -> span.spanContext.sampled = false throw IllegalStateException("callback failed") - } + }, ) assertThat(executeQueryImplementation(sut.query(LaunchDetailsQuery("83"))).data).isNotNull() @@ -465,7 +465,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 69d4db93866..d3628be16f3 100644 --- a/sentry-compose/build.gradle.kts +++ b/sentry-compose/build.gradle.kts @@ -142,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/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/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 407c5d2f748..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 @@ -688,7 +688,7 @@ class ComposeGestureTargetLocatorTest { config.set(SemanticsPropertyKey("TestTag") { s: String?, _: String? -> s }, tag) return config } - } + }, ) return modifierInfo } @@ -706,7 +706,7 @@ class ComposeGestureTargetLocatorTest { } return config } - } + }, ) return modifierInfo } @@ -718,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 4330a49e22d..c06f236ea51 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 ab160faac40..e6fba7b8326 100644 --- a/sentry-jul/src/test/kotlin/io/sentry/jul/SentryHandlerTest.kt +++ b/sentry-jul/src/test/kotlin/io/sentry/jul/SentryHandlerTest.kt @@ -282,7 +282,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") @@ -409,7 +409,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")) } @@ -430,7 +430,7 @@ class SentryHandlerTest { checkLogs { event -> assertEquals(SentryLogLevel.TRACE, event.items.first().level) assertEquals("auto.log.jul", event.items.first().attributes?.get("sentry.origin")?.value) - } + }, ) } @@ -502,7 +502,7 @@ class SentryHandlerTest { val log = logs.items.first() assertEquals("testing message without parameters", log.body) assertNull(log.attributes?.get("sentry.message.template")) - } + }, ) } @@ -520,7 +520,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) - } + }, ) } @@ -538,7 +538,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) - } + }, ) } @@ -560,7 +560,7 @@ class SentryHandlerTest { ) assertEquals(1, log.attributes?.get("sentry.message.parameter.0")?.value) assertNull(log.attributes?.get("sentry.message.parameter.1")) - } + }, ) } @@ -582,7 +582,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/src/main/java/io/sentry/ktorClient/SentryKtorClientPlugin.kt b/sentry-ktor-client/src/main/java/io/sentry/ktorClient/SentryKtorClientPlugin.kt index 0109aeb9fbc..45bfdeb8862 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 @@ -246,7 +246,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/test/java/io/sentry/ktorClient/SentryKtorClientPluginTest.kt b/sentry-ktor-client/src/test/java/io/sentry/ktorClient/SentryKtorClientPluginTest.kt index 55a87e9ad9d..99d4c05be08 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 @@ -78,7 +78,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 +118,7 @@ class SentryKtorClientPluginTest { .addHeader("myResponseHeader", "myValue") .addHeader("Set-Cookie", "theme=dark; Path=/") .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) return HttpClient(httpClientEngine) { @@ -457,7 +457,7 @@ class SentryKtorClientPluginTest { beforeSpan = { span, _ -> span.spanContext.sampled = false error("callback failed") - } + }, ) fixture.sentryTracer.spanContext.sampled = sampled fixture.options.onDiscard = onDiscard @@ -481,7 +481,7 @@ class SentryKtorClientPluginTest { beforeSpan = { span, _ -> span.description = "partially modified" throw failure - } + }, ) fixture.options.isDebug = true fixture.options.setLogger(logger) @@ -536,7 +536,7 @@ class SentryKtorClientPluginTest { beforeSpan = { span, _ -> span.description = "changed" span - } + }, ) sut.use { sut.get(fixture.server.url("/hello").toString()) } val span = fixture.sentryTracer.children.single() @@ -699,8 +699,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 66a05bf2e59..15decc64c72 100644 --- a/sentry-log4j2/build.gradle.kts +++ b/sentry-log4j2/build.gradle.kts @@ -66,7 +66,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 c32459ea022..c32853a3f63 100644 --- a/sentry-log4j2/src/test/kotlin/io/sentry/log4j2/SentryAppenderTest.kt +++ b/sentry-log4j2/src/test/kotlin/io/sentry/log4j2/SentryAppenderTest.kt @@ -102,7 +102,7 @@ class SentryAppenderTest { ILoggerBatchProcessorFactory { options, client -> LoggerBatchProcessor(options, client, ImmediateExecutorService()) } - } + }, ) loggerContext.start() @@ -268,7 +268,7 @@ class SentryAppenderTest { "auto.log.log4j2", event.items.first().attributes?.get("sentry.origin")?.value, ) - } + }, ) } @@ -441,7 +441,7 @@ class SentryAppenderTest { it.packageSet.any { pkg -> "maven:io.sentry:sentry-log4j2" == pkg.name && BuildConfig.VERSION_NAME == pkg.version - } + }, ) assertTrue(it.integrationSet.contains("Log4j")) } @@ -557,7 +557,7 @@ class SentryAppenderTest { val log = logs.items.first() assertEquals("testing message without parameters", log.body) assertNull(log.attributes?.get("sentry.message.template")) - } + }, ) } @@ -575,7 +575,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) - } + }, ) } @@ -598,7 +598,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")) - } + }, ) } @@ -620,7 +620,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 bb10c5ede9c..68c8824d284 100644 --- a/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt +++ b/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt @@ -481,7 +481,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) - } + }, ) } @@ -502,7 +502,7 @@ class SentryAppenderTest { val attributes = log.attributes!! assertNull(attributes["sentry.message.template"]) assertNull(attributes["sentry.message.parameter.0"]) - } + }, ) } @@ -528,7 +528,7 @@ class SentryAppenderTest { val attributes = log.attributes!! assertEquals("Testing {} level", attributes["sentry.message.template"]?.value) assertEquals("TRACE", attributes["sentry.message.parameter.0"]?.value) - } + }, ) } @@ -555,7 +555,7 @@ class SentryAppenderTest { val attributes = log.attributes!! assertEquals("Testing {} level", attributes["sentry.message.template"]?.value) assertEquals("TRACE", attributes["sentry.message.parameter.0"]?.value) - } + }, ) } @@ -671,7 +671,7 @@ class SentryAppenderTest { it.packageSet.any { pkg -> "maven:io.sentry:sentry-logback" == pkg.name && BuildConfig.VERSION_NAME == pkg.version - } + }, ) assertTrue(it.integrationSet.contains("Logback")) } @@ -735,7 +735,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") @@ -776,7 +776,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 }, ) } @@ -823,7 +823,7 @@ class SentryAppenderTest { val log = logs.items.first() assertEquals("testing message without parameters", log.body) assertNull(log.attributes?.get("sentry.message.template")) - } + }, ) } @@ -841,7 +841,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) - } + }, ) } @@ -864,7 +864,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")) - } + }, ) } @@ -890,7 +890,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")) - } + }, ) } @@ -917,7 +917,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") - } + }, ) } @@ -943,7 +943,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) - } + }, ) } @@ -964,7 +964,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 bdd680ac662..b7c55b74d41 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/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 3f47b4f6e17..8813d3fcabf 100644 --- a/sentry-openfeign/src/test/kotlin/io/sentry/openfeign/SentryFeignClientTest.kt +++ b/sentry-openfeign/src/test/kotlin/io/sentry/openfeign/SentryFeignClientTest.kt @@ -121,8 +121,8 @@ class SentryFeignClientTest { listOf( "thirdPartyBaggage=someValue", "secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", - ) - ) + ), + ), ) val recorderRequest = @@ -134,8 +134,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")) @@ -307,7 +307,7 @@ class SentryFeignClientTest { beforeSpan = { span, _, _ -> span.spanContext.sampled = false throw IllegalStateException("callback failed") - } + }, ) fixture.sentryTracer.spanContext.sampled = sampled fixture.sentryOptions.onDiscard = onDiscard @@ -333,7 +333,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 67c9feea2d6..47da060ae57 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-agent/build.gradle.kts +++ b/sentry-opentelemetry/sentry-opentelemetry-agent/build.gradle.kts @@ -218,7 +218,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 2583f4a0469..93b11eff4ab 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 @@ -120,7 +120,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); @@ -146,7 +146,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()); } @@ -177,8 +177,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()); } @@ -384,7 +384,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()); @@ -512,15 +512,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/main/java/io/sentry/opentelemetry/SentrySpanProcessor.java b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySpanProcessor.java index 31bd6368318..7da9917807a 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySpanProcessor.java +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySpanProcessor.java @@ -131,7 +131,6 @@ public void onStart(final @NotNull Context parentContext, final @NotNull ReadWri traceData.getBaggage(), spanId, scopes.getOptions())); - ; transactionContext.setName(transactionName); transactionContext.setTransactionNameSource(transactionNameSource); transactionContext.setOperation(op); @@ -326,12 +325,11 @@ private void updateSpanWithOtelData( spanData .getAttributes() - .forEach( - (attributeKey, value) -> { - if (value != null) { - sentrySpan.setData(attributeKey.getKey(), value); - } - }); + .forEach((attributeKey, value) -> { + if (value != null) { + sentrySpan.setData(attributeKey.getKey(), value); + } + }); final @NotNull OtelSpanInfo otelSpanInfo = spanDescriptionExtractor.extractSpanInfo(otelSpan.toSpanData(), null, scopes.getOptions()); @@ -369,12 +367,11 @@ private boolean hasSentryBeenInitialized() { final @NotNull Map mapWithStringKeys = new HashMap<>(); if (attributes != null) { - attributes.forEach( - (key, value) -> { - if (key != null) { - mapWithStringKeys.put(key.getKey(), value); - } - }); + attributes.forEach((key, value) -> { + if (key != null) { + mapWithStringKeys.put(key.getKey(), 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 6b9e733157d..c45cf2bec75 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 = @@ -278,8 +278,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 98d3989aaaf..237bb6c4498 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/SentrySpanProcessorTest.kt b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SentrySpanProcessorTest.kt index df2cf9596dd..61baf4ef423 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SentrySpanProcessorTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SentrySpanProcessorTest.kt @@ -103,7 +103,7 @@ class SentrySpanProcessorTest { anyOrNull(), eq(Instrumenter.OTEL), any(), - ) + ), ) .thenReturn(span) 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 d0220daf952..61a8f20bc5a 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtelSentryPropagatorTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtelSentryPropagatorTest.kt @@ -160,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) @@ -194,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 { 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 ca94bc1fad3..f92f7bcff4e 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtlpEndToEndTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtlpEndToEndTest.kt @@ -26,7 +26,7 @@ class OtlpEndToEndTest { .setTracerProvider( SdkTracerProvider.builder() .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.composite())) - .build() + .build(), ) .build() 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 3a1de5a704a..aee693598cb 100644 --- a/sentry-samples/sentry-samples-android/build.gradle.kts +++ b/sentry-samples/sentry-samples-android/build.gradle.kts @@ -38,7 +38,7 @@ plugins.withId("io.sentry.android.gradle") { InstrumentationFeature.COMPOSE, InstrumentationFeature.DATABASE, InstrumentationFeature.OKHTTP, - ) + ), ) logcat.enabled.set(false) appStart.enabled.set(false) @@ -82,7 +82,7 @@ android { "ContentDescription", "LabelFor", "HardcodedText", - ) + ), ) } @@ -270,7 +270,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/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 76b6a69f3fb..743178ae6b8 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, @@ -696,7 +696,7 @@ fun SessionReplayScreen() { } else { showDialog = false } - } + }, ) { Text("Close") } @@ -787,7 +787,7 @@ fun UserFeedbackScreen() { Icon( painter = painterResource( - id = io.sentry.compose.R.drawable.sentry_user_feedback_compose_button_logo_24 + id = io.sentry.compose.R.drawable.sentry_user_feedback_compose_button_logo_24, ), contentDescription = null, ) @@ -897,7 +897,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, @@ -914,7 +914,7 @@ fun IntegrationsScreen() { Intent( activity, io.sentry.samples.android.navigation.nav2.Nav2SetupActivity::class.java, - ) + ), ) }, modifier = Modifier, @@ -1051,37 +1051,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 index b0feb66a0e6..aa46a032a27 100644 --- 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 @@ -57,7 +57,7 @@ class WebViewActivity : AppCompatActivity() { addView(receivedView) addView(statusView) addView(webView, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)) - } + }, ) val assetLoader = 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 ca6321880b5..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 @@ -108,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) { @@ -330,7 +330,7 @@ class Nav3PagerFragment : Fragment() { override fun onPageSelected(position: Int) { currentPage = position } - } + }, ) } @@ -360,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", ), ) }, @@ -435,7 +435,7 @@ 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)", 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 index 6d64c7da45f..d607f29508d 100644 --- 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 @@ -97,7 +97,7 @@ internal fun Nav3OpenPlainActivityButton(modifier: Modifier = Modifier) { .putExtra( EXTRA_ENABLE_USER_INTERACTION_BREADCRUMBS, options.enableUserInteractionBreadcrumbs, - ) + ), ) }, modifier = modifier, @@ -123,11 +123,11 @@ private fun PlainNav3Screen(title: String, onBack: (() -> Unit)? = null) { 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." + "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"))) 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 92a7cbbd6bb..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 @@ -281,7 +281,7 @@ internal fun RouteScaffold( Modifier.fillMaxSize() .background(MaterialTheme.colorScheme.background) .padding(16.dp) - .testTag("${testTagPrefix}_screen") + .testTag("${testTagPrefix}_screen"), ) { Column( modifier = @@ -448,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( @@ -526,7 +526,7 @@ internal fun ProductListRoute(backStack: SnapshotStateList) { productId = "42", source = "product-list", campaign = "summer-sale", - ) + ), ) }, testTag = nav3TestTag("product_list_open_product_42"), @@ -779,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/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 c443c9a8bd5..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( 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 d973a68a907..ddc3ce62a00 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,141 +22,131 @@ 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; - // } - // }); - - options.getLogs().setEnabled(true); - }); + 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; + // } + // }); + + options.getLogs().setEnabled(true); + }); 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 968feb5a1b7..58fcd73d189 100644 --- a/sentry-samples/sentry-samples-netflix-dgs/build.gradle.kts +++ b/sentry-samples/sentry-samples-netflix-dgs/build.gradle.kts @@ -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/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-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/TodoController.java b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/TodoController.java index e5f395ec2b5..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 @@ -36,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/TodoController.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/TodoController.java index c5093bc9cf5..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 @@ -55,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/TodoController.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/TodoController.java index c5093bc9cf5..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 @@ -55,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/TodoController.java b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/TodoController.java index 9a4dd98c90b..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 @@ -36,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/TodoController.java b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/TodoController.java index 0bbe0643495..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 @@ -52,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 df3cd548218..270b1da4bdc 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 4dd05110bbf..f2ef9ed1195 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 @@ -133,10 +133,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 24f32e77f88..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 @@ -29,9 +29,9 @@ class SentrySpringSubscriptionHandlerTest { .operation(OperationDefinition.Operation.QUERY) .name("testQuery") .selectionSet( - SelectionSet.newSelectionSet().selection(Field.newField("test").build()).build() + SelectionSet.newSelectionSet().selection(Field.newField("test").build()).build(), ) - .build() + .build(), ) .build() 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/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 734bd5d8a5c..78721b478e1 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 @@ -174,12 +174,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-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 58de0bc4b26..64c7d98f23f 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,26 +39,25 @@ 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(); - 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); + 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/test/kotlin/io/sentry/spring/boot4/SentryAutoConfigurationTest.kt b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryAutoConfigurationTest.kt index 334153d4e86..5885635578f 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 @@ -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) } @@ -604,7 +604,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() @@ -917,7 +917,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -929,7 +929,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -944,7 +944,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -960,7 +960,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryNoAgent") + .contains("SpringBoot4OpenTelemetryNoAgent"), ) } } @@ -975,7 +975,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryNoAgent") + .contains("SpringBoot4OpenTelemetryNoAgent"), ) } } @@ -989,14 +989,14 @@ class SentryAutoConfigurationTest { FilteredClassLoader( AgentMarker::class.java, SentryAutoConfigurationCustomizerProvider::class.java, - ) + ), ) .withUserConfiguration(OtelBeanConfig::class.java) .run { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryNoAgent") + .contains("SpringBoot4OpenTelemetryNoAgent"), ) } } @@ -1011,7 +1011,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -1067,7 +1067,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) @@ -1135,7 +1135,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\"") @@ -1201,7 +1201,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 bc6d8c88ca3..06fd6d1f83d 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 @@ -32,7 +32,7 @@ class SentryLog4j2AppenderAutoConfigurationTest { AutoConfigurations.of( SentryLog4j2AppenderAutoConfiguration::class.java, SentryAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( "sentry.shutdownTimeoutMillis=0", @@ -138,7 +138,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) } @@ -264,7 +264,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 681932e6f89..8667c8177c3 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 9b35c0e2abc..3d6756133f3 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 @@ -80,7 +80,7 @@ class SentrySpanRestClientCustomizerTest { sentryOptions.isTraceSampling = true 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-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 381a10975f6..f63be76a8b3 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 @@ -84,7 +84,7 @@ class SentrySpanRestTemplateCustomizerTest { sentryOptions.isTraceSampling = true mockServer.enqueue( - MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()) + MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()), ) if (isTransactionActive) { @@ -142,8 +142,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")) @@ -230,8 +230,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/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 aaa91afa424..b42a9070b5a 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 @@ -176,12 +176,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 be222eae1bf..8379df4d214 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,26 +39,25 @@ 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(); - 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); + 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 4f602db34f4..0674b908a94 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 @@ -110,7 +110,7 @@ class SentryAutoConfigurationTest { SentryAutoConfiguration::class.java, WebMvcAutoConfiguration::class.java, SentryProfilerAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -131,7 +131,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 @@ -139,14 +139,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 @@ -200,7 +200,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 } @@ -210,7 +210,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() } @@ -226,7 +226,7 @@ class SentryAutoConfigurationTest { it .getBean(SentryProperties::class.java) .graphql - .isEnableSpecificationErrorTypeFiltering + .isEnableSpecificationErrorTypeFiltering, ) .isEqualTo(enabled) } @@ -623,7 +623,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() @@ -936,7 +936,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -948,7 +948,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -963,7 +963,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -979,7 +979,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryNoAgent") + .contains("SpringBoot3OpenTelemetryNoAgent"), ) } } @@ -994,7 +994,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryNoAgent") + .contains("SpringBoot3OpenTelemetryNoAgent"), ) } } @@ -1008,14 +1008,14 @@ class SentryAutoConfigurationTest { FilteredClassLoader( AgentMarker::class.java, SentryAutoConfigurationCustomizerProvider::class.java, - ) + ), ) .withUserConfiguration(OtelBeanConfig::class.java) .run { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryNoAgent") + .contains("SpringBoot3OpenTelemetryNoAgent"), ) } } @@ -1030,7 +1030,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -1086,7 +1086,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) @@ -1154,7 +1154,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\"") @@ -1220,7 +1220,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 7cdb97cfc9a..7a1859601c0 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 @@ -32,7 +32,7 @@ class SentryLog4j2AppenderAutoConfigurationTest { AutoConfigurations.of( SentryLog4j2AppenderAutoConfiguration::class.java, SentryAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( "sentry.shutdownTimeoutMillis=0", @@ -138,7 +138,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) } @@ -264,7 +264,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 d8982d995c1..5ede217a526 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 ac38f48047a..0849a619e37 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 @@ -80,7 +80,7 @@ class SentrySpanRestClientCustomizerTest { sentryOptions.isTraceSampling = true mockServer.enqueue( - MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()) + MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()), ) if (isTransactionActive) { @@ -157,8 +157,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")) @@ -272,8 +272,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 e30c2e99d72..6fab71f5847 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 @@ -84,7 +84,7 @@ class SentrySpanRestTemplateCustomizerTest { sentryOptions.isTraceSampling = true mockServer.enqueue( - MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()) + MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()), ) if (isTransactionActive) { @@ -142,8 +142,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")) @@ -230,8 +230,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/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 744fa9d739a..2fb4437aaad 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 @@ -171,12 +171,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 94ba7b743fe..d475dabb8b0 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,26 +39,25 @@ 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(); - 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); + 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 f4f14c6a85e..acce51df8cb 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 @@ -109,7 +109,7 @@ class SentryAutoConfigurationTest { SentryAutoConfiguration::class.java, WebMvcAutoConfiguration::class.java, SentryProfilerAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -130,7 +130,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 @@ -138,14 +138,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 @@ -198,7 +198,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 } @@ -208,7 +208,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() } @@ -224,7 +224,7 @@ class SentryAutoConfigurationTest { it .getBean(SentryProperties::class.java) .graphql - .isEnableSpecificationErrorTypeFiltering + .isEnableSpecificationErrorTypeFiltering, ) .isEqualTo(enabled) } @@ -621,7 +621,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() @@ -927,7 +927,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryAgentWithoutAutoInit") + .contains("SpringBootOpenTelemetryAgentWithoutAutoInit"), ) } } @@ -939,7 +939,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryAgentWithoutAutoInit") + .contains("SpringBootOpenTelemetryAgentWithoutAutoInit"), ) } } @@ -954,7 +954,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryAgentWithoutAutoInit") + .contains("SpringBootOpenTelemetryAgentWithoutAutoInit"), ) } } @@ -970,7 +970,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryNoAgent") + .contains("SpringBootOpenTelemetryNoAgent"), ) } } @@ -985,7 +985,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryNoAgent") + .contains("SpringBootOpenTelemetryNoAgent"), ) } } @@ -999,14 +999,14 @@ class SentryAutoConfigurationTest { FilteredClassLoader( AgentMarker::class.java, SentryAutoConfigurationCustomizerProvider::class.java, - ) + ), ) .withUserConfiguration(OtelBeanConfig::class.java) .run { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryNoAgent") + .contains("SpringBootOpenTelemetryNoAgent"), ) } } @@ -1021,7 +1021,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryAgentWithoutAutoInit") + .contains("SpringBootOpenTelemetryAgentWithoutAutoInit"), ) } } @@ -1040,7 +1040,7 @@ class SentryAutoConfigurationTest { assertThat(it) .getBean(IProfileConverter::class.java) .isInstanceOf( - AsyncProfilerProfileConverterProvider.AsyncProfilerProfileConverter::class.java + AsyncProfilerProfileConverterProvider.AsyncProfilerProfileConverter::class.java, ) assertThat(it) .getBean(IContinuousProfiler::class.java) @@ -1191,7 +1191,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 f68cad0ff90..ed11b016fe4 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 7fcba218af4..dea5a175bb4 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 @@ -84,7 +84,7 @@ class SentrySpanRestTemplateCustomizerTest { sentryOptions.isTraceSampling = true mockServer.enqueue( - MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()) + MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()), ) if (isTransactionActive) { @@ -142,8 +142,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")) @@ -230,8 +230,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 1920a8f6ea2..3ffa721c0c8 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 84af5a708e0..6e3b0457e0f 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 @@ -133,10 +133,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 eda50c41af2..f650ee4c053 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 30d1152b88a..a592dde46a2 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 @@ -77,41 +77,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) { @@ -162,10 +159,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/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/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 2ac8178d655..30df2538699 100644 --- a/sentry/src/main/java/io/sentry/Scopes.java +++ b/sentry/src/main/java/io/sentry/Scopes.java @@ -1149,13 +1149,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 b08e140392c..586a9d6c831 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 00f5729535a..8112cf0ee8b 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -468,62 +468,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() @@ -575,36 +573,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); } @@ -665,20 +661,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 2b0a97ff5c3..9e8b49b169b 100644 --- a/sentry/src/main/java/io/sentry/SentryClient.java +++ b/sentry/src/main/java/io/sentry/SentryClient.java @@ -892,45 +892,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 d1858c02767..e3fcc16ae0b 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( @@ -183,16 +179,14 @@ public static SentryEnvelopeItem fromUserFeedback( Objects.requireNonNull(userFeedback, "UserFeedback 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(userFeedback, 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(userFeedback, writer); + return stream.toByteArray(); + } + }); SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( @@ -212,16 +206,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( @@ -239,40 +231,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( @@ -317,59 +306,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( @@ -406,40 +392,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( @@ -468,40 +452,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( @@ -522,16 +503,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( @@ -566,53 +545,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( @@ -629,16 +606,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( @@ -661,16 +636,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 cc1ce8e22ac..acc35f742ae 100644 --- a/sentry/src/main/java/io/sentry/SentryTracer.java +++ b/sentry/src/main/java/io/sentry/SentryTracer.java @@ -211,24 +211,23 @@ 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 = - transactionOptions.getTransactionFinishedCallback(); - 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 = + transactionOptions.getTransactionFinishedCallback(); + 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 @@ -253,15 +252,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); @@ -1036,10 +1033,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/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/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 8a1aa0ac660..4e6d29a29b7 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 d259100853c..5726b6ca25c 100644 --- a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt +++ b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt @@ -243,14 +243,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 8fb929224ea..9786f90cb50 100644 --- a/sentry/src/test/java/io/sentry/DuplicateEventDetectionEventProcessorTest.kt +++ b/sentry/src/test/java/io/sentry/DuplicateEventDetectionEventProcessorTest.kt @@ -66,7 +66,7 @@ class DuplicateEventDetectionEventProcessorTest { val result = processor.process( SentryEvent( - ExceptionMechanismException(Mechanism(), event.throwable!!, Thread.currentThread()) + ExceptionMechanismException(Mechanism(), event.throwable!!, Thread.currentThread()), ), Hint(), ) @@ -78,7 +78,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 cdd184b181f..1f90722d115 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) @@ -343,12 +343,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"), + ), ) } } @@ -397,7 +397,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")), ) } } @@ -466,7 +466,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 95b664e13a9..82f5dc7d5b3 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) @@ -1601,7 +1601,7 @@ class JsonSerializerTest { listOf( Breadcrumb(timestamp).apply { message = "test" }, Breadcrumb(timestamp).apply { category = "navigation" }, - ) + ), ) val deserializedCollection = @@ -1725,7 +1725,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 37bf1efef98..93cb017f48c 100644 --- a/sentry/src/test/java/io/sentry/JsonUnknownSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/JsonUnknownSerializationTest.kt @@ -73,7 +73,7 @@ class JsonUnknownSerializationTest( SentryPackage( "b59a1949-9950-4203-b394-ddd8d02c9633", "3d7790f3-7f32-43f7-b82f-9f5bc85205a8", - ) + ), ) val sentryRuntime = givenJsonUnknown(SentryRuntime()) val sentrySpan = givenJsonUnknown(SentrySpanSerializationTest.Fixture().getSut()) @@ -86,7 +86,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/NoOpTransactionTest.kt b/sentry/src/test/java/io/sentry/NoOpTransactionTest.kt index a1a81d37407..72042c85a13 100644 --- a/sentry/src/test/java/io/sentry/NoOpTransactionTest.kt +++ b/sentry/src/test/java/io/sentry/NoOpTransactionTest.kt @@ -18,7 +18,13 @@ class NoOpTransactionTest { assertNotNull(transaction.startChild("op", "desc", SentryNanotimeDate())) assertNotNull(transaction.startChild("op", "desc", SentryNanotimeDate(), Instrumenter.SENTRY)) assertNotNull( - transaction.startChild("op", "desc", SentryNanotimeDate(), Instrumenter.SENTRY, SpanOptions()) + transaction.startChild( + "op", + "desc", + SentryNanotimeDate(), + Instrumenter.SENTRY, + SpanOptions(), + ), ) } 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/PreviousSessionFinalizerTest.kt b/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt index 4c8510facca..f9a3097ec7d 100644 --- a/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt +++ b/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt @@ -118,7 +118,7 @@ class PreviousSessionFinalizerTest { val sessionCreationToFinalizerInterval = 20000 val sessionCreationTimestamp = DateUtils.getDateTime( - DateUtils.getCurrentDateTime().time - sessionCreationToFinalizerInterval + DateUtils.getCurrentDateTime().time - sessionCreationToFinalizerInterval, ) val finalizer = @@ -154,7 +154,7 @@ class PreviousSessionFinalizerTest { captureTimestamp - session.started!!.time > sessionCreationToFinalizerInterval && session.timestamp!!.time != sessionCreationTimestamp.time && captureTimestamp - session.timestamp!!.time < 1000 - } + }, ) } @@ -177,7 +177,7 @@ class PreviousSessionFinalizerTest { argThat { val session = fixture.sessionFromEnvelope(this) session.release == "io.sentry.sample@1.0" && session.timestamp!! == abnormalEndDate - } + }, ) } @@ -196,7 +196,7 @@ class PreviousSessionFinalizerTest { argThat { val session = fixture.sessionFromEnvelope(this) session.release == "io.sentry.sample@1.0" && session.status == Crashed - } + }, ) } @@ -219,7 +219,7 @@ class PreviousSessionFinalizerTest { session.release == "io.sentry.sample@1.0" && session.status == Session.State.Unhandled && session.hasNonTerminatingUnhandledError() - } + }, ) } @@ -241,7 +241,7 @@ class PreviousSessionFinalizerTest { argThat { val session = fixture.sessionFromEnvelope(this) session.release == "io.sentry.sample@1.0" && session.status == Crashed - } + }, ) } @@ -277,7 +277,7 @@ 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.", ) }, ) diff --git a/sentry/src/test/java/io/sentry/ScopeTest.kt b/sentry/src/test/java/io/sentry/ScopeTest.kt index 3fb19078c27..d6cd6f7c1df 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 @@ -1181,7 +1181,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()) }, ) } @@ -1319,7 +1319,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 8e55d4fbc5b..253c054531c 100644 --- a/sentry/src/test/java/io/sentry/ScopesTest.kt +++ b/sentry/src/test/java/io/sentry/ScopesTest.kt @@ -801,7 +801,7 @@ class ScopesTest { assertEquals(userFeedback.email, it.email) assertEquals(userFeedback.name, it.name) assertEquals(userFeedback.comments, it.comments) - } + }, ) } @@ -1591,7 +1591,7 @@ class ScopesTest { anyOrNull(), anyOrNull(), anyOrNull(), - ) + ), ) .thenReturn(SentryId()) @@ -2307,7 +2307,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", ), ) @@ -2329,7 +2329,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", ), ) @@ -2356,7 +2356,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", ), ) @@ -2380,7 +2380,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", ), ) @@ -2405,7 +2405,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", ), ) @@ -2559,7 +2559,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.", ), ) } @@ -2613,7 +2613,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.", ), ) } @@ -2960,7 +2960,7 @@ class ScopesTest { SentryAttribute.named("namedintattr", 18), SentryAttribute.named("nameddoubleattr", 4.9), SentryAttribute.named("namedarrayattr", listOf("x", "y")), - ) + ), ), "log message", ) @@ -3720,7 +3720,7 @@ class ScopesTest { SentryAttribute.named("namedintattr", 18), SentryAttribute.named("nameddoubleattr", 4.9), SentryAttribute.named("namedarrayattr", listOf("x", "y")), - ) + ), ), ) @@ -3899,7 +3899,7 @@ class ScopesTest { SentryAttribute.named("namedintattr", 18), SentryAttribute.named("nameddoubleattr", 4.9), SentryAttribute.named("namedarrayattr", listOf("x", "y")), - ) + ), ), ) @@ -4078,7 +4078,7 @@ class ScopesTest { SentryAttribute.named("namedintattr", 18), SentryAttribute.named("nameddoubleattr", 4.9), SentryAttribute.named("namedarrayattr", listOf("x", "y")), - ) + ), ), ) @@ -4551,7 +4551,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 { @@ -4565,7 +4565,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 e04cadf624f..af3be5847ec 100644 --- a/sentry/src/test/java/io/sentry/SentryClientTest.kt +++ b/sentry/src/test/java/io/sentry/SentryClientTest.kt @@ -467,7 +467,7 @@ class SentryClientTest { scope.addEventProcessor( object : EventProcessor { override fun process(event: SentryLogEvent): SentryLogEvent? = null - } + }, ) val sut = fixture.getSut() @@ -630,7 +630,7 @@ class SentryClientTest { scope.addEventProcessor( object : EventProcessor { override fun process(event: SentryMetricsEvent, hint: Hint): SentryMetricsEvent? = null - } + }, ) val sut = fixture.getSut() @@ -1065,7 +1065,7 @@ class SentryClientTest { assertEquals("application/json", item.header.contentType) assertEnvelopeItemDataForUserFeedback(item) - } + }, ) } @@ -1590,7 +1590,7 @@ class SentryClientTest { transaction.spans.removeIf { it.description != "span2" } return transaction } - } + }, ) fixture.getSut().captureTransaction(transaction, scope, null) @@ -2250,7 +2250,7 @@ class SentryClientTest { assertEquals(1, images.size) assertEquals(DebugImage.PROGUARD, images[0].type) assertEquals("current-uuid", images[0].uuid) - } + }, ) } @@ -2264,7 +2264,7 @@ class SentryClientTest { DebugImage().apply { type = DebugImage.PROGUARD uuid = "previous-uuid" - } + }, ) } @@ -2280,7 +2280,7 @@ class SentryClientTest { assertEquals(1, images.size) assertEquals(DebugImage.PROGUARD, images[0].type) assertEquals("previous-uuid", images[0].uuid) - } + }, ) } @@ -2525,7 +2525,7 @@ class SentryClientTest { } override fun registerSegmentName(segmentName: String) {} - } + }, ) val sut = fixture.getSut() val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.scopes) @@ -2542,7 +2542,7 @@ class SentryClientTest { override fun registerSegmentName(segmentName: String) { registeredSegmentName = segmentName } - } + }, ) val sut = fixture.getSut() val sentryTracer = @@ -3119,7 +3119,7 @@ class SentryClientTest { override fun process(transaction: SentryTransaction, hint: Hint): SentryTransaction? { return transaction } - } + }, ) } @@ -3143,7 +3143,7 @@ class SentryClientTest { override fun process(transaction: SentryTransaction, hint: Hint): SentryTransaction? { return transaction } - } + }, ) } @@ -3208,7 +3208,7 @@ class SentryClientTest { hint.addAttachment(fixture.attachment3) return transaction } - } + }, ) } @@ -3242,7 +3242,7 @@ class SentryClientTest { hint.replaceAttachments(listOf(fixture.attachment3)) return transaction } - } + }, ) } @@ -3819,7 +3819,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -3836,7 +3836,7 @@ class SentryClientTest { terminated = isTerminating return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -3844,7 +3844,7 @@ class SentryClientTest { SentryEvent().apply { exceptions = listOf(SentryException().apply { mechanism = Mechanism().apply { isHandled = false } }) - } + }, ) assertTrue(terminated == true) } @@ -3855,7 +3855,7 @@ class SentryClientTest { fixture.sentryOptions.setReplayController( object : ReplayController by NoOpReplayController.getInstance() { override fun captureReplay(isTerminating: Boolean?): SentryId = replayId - } + }, ) val sut = fixture.getSut() @@ -3916,7 +3916,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -3939,7 +3939,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -3980,7 +3980,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) fixture.sentryOptions.sessionReplay.beforeErrorSampling = SentryReplayOptions.BeforeErrorSamplingCallback { _, _ -> @@ -4001,7 +4001,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) fixture.sentryOptions.sessionReplay.beforeErrorSampling = SentryReplayOptions.BeforeErrorSamplingCallback { _, _ -> @@ -4022,7 +4022,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -4049,7 +4049,7 @@ class SentryClientTest { SentryEvent().apply { exceptions = listOf( - SentryException().apply { mechanism = Mechanism().apply { isHandled = handled } } + SentryException().apply { mechanism = Mechanism().apply { isHandled = handled } }, ) } } @@ -4112,7 +4112,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 -> @@ -4138,7 +4138,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -4417,7 +4417,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), ), ) @@ -4436,7 +4436,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), ), ) @@ -4465,7 +4465,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) @@ -4576,7 +4576,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), ) } } @@ -4693,7 +4693,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 } @@ -4725,7 +4725,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 284c0a98cd5..1a6bbb6148b 100644 --- a/sentry/src/test/java/io/sentry/SentryOptionsTest.kt +++ b/sentry/src/test/java/io/sentry/SentryOptionsTest.kt @@ -339,7 +339,7 @@ class SentryOptionsTest { assertTrue( sdkVersion.packageSet.any { it.name == "maven:io.sentry:sentry" && it.version == BuildConfig.VERSION_NAME - } + }, ) } @@ -558,7 +558,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 @@ -853,11 +853,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 0ccfb79d699..24406d541ba 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -653,7 +653,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" }) @@ -840,7 +840,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(), ) @@ -1231,7 +1231,7 @@ class SentryTest { assertEquals("app.launch", it.transactionContext.name) assertEquals("profile", it.transactionContext.operation) assertTrue(it.transactionContext.isForNextAppStart) - } + }, ) verify(mockProfilesSampler) .sample( @@ -1239,7 +1239,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 20232f56b4d..41af30d1d34 100644 --- a/sentry/src/test/java/io/sentry/SentryTracerTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTracerTest.kt @@ -102,11 +102,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) @@ -115,11 +117,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") @@ -129,11 +133,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) @@ -218,7 +224,7 @@ class SentryTracerTest { optionsConfiguration = { it.profilesSampleRate = 0.0 it.setTransactionProfiler(transactionProfiler) - } + }, ) tracer.finish() verify(transactionProfiler, never()).onTransactionFinish(any(), anyOrNull(), anyOrNull()) @@ -461,7 +467,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) @@ -509,7 +515,7 @@ class SentryTracerTest { fixture.getSut( optionsConfiguration = { options -> options.setContinuousProfiler(NoOpContinuousProfiler.getInstance()) - } + }, ) val span = tracer.startChild("span.op") assertNull(span.getData(SpanDataConvention.PROFILER_ID)) @@ -911,10 +917,12 @@ class SentryTracerTest { @Test fun `returns trace state`() { val transaction = - fixture.getSut({ - it.isTraceSampling = true - it.isSendDefaultPii = true - }) + fixture.getSut( + { + it.isTraceSampling = true + it.isSendDefaultPii = true + }, + ) fixture.scopes.setUser(User().apply { id = "user-id" }) val replayId = SentryId() fixture.scopes.configureScope { it.replayId = replayId } @@ -986,12 +994,14 @@ class SentryTracerTest { @Test fun `returns baggage header`() { val transaction = - fixture.getSut({ - it.isTraceSampling = true - it.environment = "production" - it.release = "1.0.99-rc.7" - it.isSendDefaultPii = true - }) + fixture.getSut( + { + it.isTraceSampling = true + it.environment = "production" + it.release = "1.0.99-rc.7" + it.isSendDefaultPii = true + }, + ) fixture.scopes.setUser(User().apply { id = "userId12345" }) val replayId = SentryId() @@ -1015,11 +1025,13 @@ class SentryTracerTest { @Test fun `returns baggage header without userId if not send pii`() { val transaction = - fixture.getSut({ - it.isTraceSampling = true - it.environment = "production" - it.release = "1.0.99-rc.7" - }) + fixture.getSut( + { + it.isTraceSampling = true + it.environment = "production" + it.release = "1.0.99-rc.7" + }, + ) fixture.scopes.setUser(User().apply { id = "userId12345" }) @@ -1040,12 +1052,14 @@ class SentryTracerTest { @Test fun `returns baggage header without userId if send pii and null user`() { val transaction = - fixture.getSut({ - it.isTraceSampling = true - it.environment = "production" - it.release = "1.0.99-rc.7" - it.isSendDefaultPii = true - }) + fixture.getSut( + { + it.isTraceSampling = true + it.environment = "production" + it.release = "1.0.99-rc.7" + it.isSendDefaultPii = true + }, + ) fixture.scopes.setUser(null) @@ -1841,7 +1855,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 b61e12ad87f..ef22f65ce54 100644 --- a/sentry/src/test/java/io/sentry/SpanTest.kt +++ b/sentry/src/test/java/io/sentry/SpanTest.kt @@ -29,7 +29,7 @@ class SpanTest { SentryOptions().apply { dsn = "https://key@sentry.io/proj" isTraceSampling = true - } + }, ) } @@ -373,7 +373,7 @@ class SpanTest { SpanOptions().apply { isTrimStart = true isTrimEnd = true - } + }, ) // and two child spans are started @@ -408,7 +408,7 @@ class SpanTest { TransactionOptions().apply { isTrimStart = true isTrimEnd = true - } + }, ) // and two child spans are started @@ -573,7 +573,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 e077b25fb3c..a8b631a1d59 100644 --- a/sentry/src/test/java/io/sentry/clientreport/ClientReportTest.kt +++ b/sentry/src/test/java/io/sentry/clientreport/ClientReportTest.kt @@ -202,7 +202,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) @@ -322,7 +322,7 @@ class ClientReportTest { ChronoUnit.MILLIS.between( LocalDateTime.now(), envelopeReport.timestamp.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), - ) < 10000 + ) < 10000, ) } @@ -343,7 +343,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 } @@ -377,9 +377,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()) @@ -409,9 +409,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()) @@ -579,7 +579,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 00ba9cd9872..eda14e5fb7c 100644 --- a/sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt +++ b/sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt @@ -506,7 +506,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)) @@ -531,7 +531,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 caa93f1af7a..2b53aa0116c 100644 --- a/sentry/src/test/java/io/sentry/util/JsonSerializationUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/JsonSerializationUtilsTest.kt @@ -48,7 +48,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 8fa8eb05ef3..5cd50d6486e 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}"), ) } @@ -355,7 +355,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", From 53bf81d1db21d04409a264a73c32aa8301e0229b Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:16:19 +0100 Subject: [PATCH 41/51] ci: Add PR risk (Jev) workflow (#6615) * ci: Add PR risk (Jev) workflow Copy getsentry/toolkit's pr-risk-jev.yml, which labels non-draft PRs risk: low/medium/high via getsentry/pr-risk-action. Pin actions/upload-artifact to the SHA the other workflows here use. Co-Authored-By: Nelson Osacky * ci: Bump pr-risk-action and align github-script pin Pin pr-risk-action to the latest main commit, which bumps Node to 22.23.4 for a security fix. Use the github-script v9.0.0 SHA the other workflows in this repo already use. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Nelson Osacky Co-authored-by: Claude Opus 5.5 --- .github/workflows/pr-risk-jev.yml | 120 ++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 .github/workflows/pr-risk-jev.yml 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 From cb42c8720b83d256752b335b84235a26971d8c07 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Mon, 16 Nov 2026 12:34:52 +0100 Subject: [PATCH 42/51] build(deps): Bump Room 3 to 3.0.3 (#6616) Room 3 is now stable, so move off 3.0.0-rc01. Room 3.0.3 only needs androidx.sqlite 2.7.x, so the sample's SQLite drivers go back from 2.8.0-alpha03 to stable 2.7.1. The sqliteRc catalog key is renamed to sqliteDrivers since it no longer tracks an RC, which also stops Dependabot from picking pre-releases for it. Co-authored-by: Claude Opus 5.5 --- gradle/libs.versions.toml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7959ada57dc..99d7fcef958 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -39,12 +39,12 @@ otelSemanticConventions = "1.44.0" otelSemanticConventionsAlpha = "1.44.0-alpha" retrofit = "3.0.0" room2 = "2.8.5" -room3 = "3.0.0-rc01" +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.5.1" 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.11.0" springboot2 = "2.7.18" @@ -129,8 +129,8 @@ androidx-room3-compiler = { module = "androidx.room3:room3-compiler", version.re 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" } From 230102302413f4162a0ad5cb552a7b2eb5139287 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:36:46 +0100 Subject: [PATCH 43/51] chore(deps): bump coroutines from 1.6.1 to 1.11.0 (#6609) Bumps `coroutines` from 1.6.1 to 1.11.0. Updates `org.jetbrains.kotlinx:kotlinx-coroutines-core` from 1.6.1 to 1.11.0 - [Release notes](https://github.com/Kotlin/kotlinx.coroutines/releases) - [Changelog](https://github.com/Kotlin/kotlinx.coroutines/blob/master/CHANGES.md) - [Commits](https://github.com/Kotlin/kotlinx.coroutines/compare/1.6.1...1.11.0) Updates `org.jetbrains.kotlinx:kotlinx-coroutines-android` from 1.6.1 to 1.11.0 - [Release notes](https://github.com/Kotlin/kotlinx.coroutines/releases) - [Changelog](https://github.com/Kotlin/kotlinx.coroutines/blob/master/CHANGES.md) - [Commits](https://github.com/Kotlin/kotlinx.coroutines/compare/1.6.1...1.11.0) Updates `org.jetbrains.kotlinx:kotlinx-coroutines-test` from 1.6.1 to 1.11.0 - [Release notes](https://github.com/Kotlin/kotlinx.coroutines/releases) - [Changelog](https://github.com/Kotlin/kotlinx.coroutines/blob/master/CHANGES.md) - [Commits](https://github.com/Kotlin/kotlinx.coroutines/compare/1.6.1...1.11.0) --- updated-dependencies: - dependency-name: org.jetbrains.kotlinx:kotlinx-coroutines-android dependency-version: 1.11.0 dependency-type: direct:production update-type: version-update:semver-minor - dependency-name: org.jetbrains.kotlinx:kotlinx-coroutines-core dependency-version: 1.11.0 dependency-type: direct:production update-type: version-update:semver-minor - dependency-name: org.jetbrains.kotlinx:kotlinx-coroutines-test dependency-version: 1.11.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 99d7fcef958..88af43cd570 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -9,7 +9,7 @@ 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" From f3bd07fa184135e903261353ea697f94fa083317 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Mon, 16 Nov 2026 14:24:27 +0100 Subject: [PATCH 44/51] fix(ktor-client): Send replay network timestamps in milliseconds (#6619) * fix(ktor-client): Send replay network timestamps in milliseconds Session Replay reads the HTTP start and end timestamps on a breadcrumb as epoch milliseconds, which is what sentry-okhttp sends. sentry-ktor-client divided the epoch nanoseconds by 1000, so it sent microseconds and its replay network spans landed 1000x too far in the future. Co-Authored-By: Claude Opus 5.5 * changelog * changelog --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../ktorClient/SentryKtorClientUtils.kt | 6 +++-- .../ktorClient/SentryKtorClientPluginTest.kt | 23 +++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f6c22e1d5f..b235002fab1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ ### Fixes +- 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)) 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 99d4c05be08..4e593bb0511 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 @@ -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") From a60174467d53e6da51402175669ce0b29c91677f Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Mon, 16 Nov 2026 14:44:10 +0100 Subject: [PATCH 45/51] chore(ai): Remove stale sentry-for-ai skills from agents.toml (#6620) getsentry/sentry-for-ai removed sentry-code-review and sentry-pr-code-review, dissolved the sentry-workflow router, and moved sentry-fix-issues to skills-legacy, which dotagents no longer resolves. Project install on main fails on the first of them. Also add --project to the dotagents commands in the header. Since dotagents 3.x the default scope is global (~/.agents/), so the commands as written do nothing for this repo. Co-authored-by: Claude Opus 5.5 --- agents.toml | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) 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" From b0796b361d43889cdaed695ad194a608d7d5c79e Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Mon, 16 Nov 2026 14:51:22 +0100 Subject: [PATCH 46/51] build(android): Include Android resources in navigation3 unit tests (#6618) AGP 9.5 registers a Compose Preview task for every Compose module and fails to create it when unit tests exclude Android resources. Normal builds never create that task, but anything that creates every task, such as an LSP's Gradle import or `./gradlew tasks --all`, fails on navigation3. Every other Android module already sets this. Co-authored-by: Claude Opus 5.5 --- sentry-android-navigation3/build.gradle.kts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index 139158f4bd9..205f6b95bd6 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -40,7 +40,12 @@ 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 { From ad273220c8b44f4edc6921dc57c706326017c3da Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:08:06 +0100 Subject: [PATCH 47/51] chore(deps): bump feign from 11.6 to 13.17 (#6606) Bumps `feign` from 11.6 to 13.17. Updates `io.github.openfeign:feign-core` from 11.6 to 13.17 - [Release notes](https://github.com/openfeign/feign/releases) - [Changelog](https://github.com/OpenFeign/feign/blob/13.17/CHANGELOG.md) - [Commits](https://github.com/openfeign/feign/compare/11.6...13.17) Updates `io.github.openfeign:feign-gson` from 11.6 to 13.17 - [Release notes](https://github.com/openfeign/feign/releases) - [Changelog](https://github.com/OpenFeign/feign/blob/13.17/CHANGELOG.md) - [Commits](https://github.com/openfeign/feign/compare/11.6...13.17) --- updated-dependencies: - dependency-name: io.github.openfeign:feign-core dependency-version: '13.17' dependency-type: direct:production update-type: version-update:semver-major - dependency-name: io.github.openfeign:feign-gson dependency-version: '13.17' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 88af43cd570..41076f4808f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -14,7 +14,7 @@ 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" java8Signature = "1.0" jackson = "2.18.3" From f56ca2a589ade86046136e68686ed0412c3bc3f3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:29:02 +0000 Subject: [PATCH 48/51] chore(deps): bump slf4j from 1.7.30 to 2.0.20 (#6536) * chore(deps): bump slf4j from 1.7.30 to 2.0.20 Bumps `slf4j` from 1.7.30 to 2.0.20. Updates `org.slf4j:slf4j-api` from 1.7.30 to 2.0.20 Updates `org.slf4j:slf4j-jdk14` from 1.7.30 to 2.0.20 --- updated-dependencies: - dependency-name: org.slf4j:slf4j-api dependency-version: 2.0.20 dependency-type: direct:production update-type: version-update:semver-major - dependency-name: org.slf4j:slf4j-jdk14 dependency-version: 2.0.20 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] * Apply suggestion from @adinauer --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Alexander Dinauer --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 41076f4808f..e1dd49ce73b 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -203,7 +203,7 @@ 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" } From 70c6fb0e96fe0748761f16e2e60a59159917ef27 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:02:33 +0100 Subject: [PATCH 49/51] chore(deps): bump com.google.devtools.ksp from 2.3.13 to 2.3.14 (#6630) Bumps [com.google.devtools.ksp](https://github.com/google/ksp) from 2.3.13 to 2.3.14. - [Release notes](https://github.com/google/ksp/releases) - [Commits](https://github.com/google/ksp/compare/2.3.13...2.3.14) --- updated-dependencies: - dependency-name: com.google.devtools.ksp dependency-version: 2.3.14 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index e1dd49ce73b..d41f654e510 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -21,7 +21,7 @@ jackson = "2.18.3" jetbrainsCompose = "1.6.11" kotlin = "2.3.21" kotlin-compatible-version = "1.9" -ksp = "2.3.13" +ksp = "2.3.14" ktorClient = "3.6.1" logback = "1.2.9" log4j2 = "2.26.1" From 3e6c07a75a0f58e530203136f16d6479458809e0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:03:03 +0100 Subject: [PATCH 50/51] chore(deps): bump androidx.annotation:annotation from 1.9.1 to 1.11.0 (#6627) Bumps androidx.annotation:annotation from 1.9.1 to 1.11.0. --- updated-dependencies: - dependency-name: androidx.annotation:annotation dependency-version: 1.11.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index d41f654e510..d0afe5ebd8a 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -97,7 +97,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" } From 9feef7524bedad299efd9d650b2b32c20d07a480 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:43:07 +0100 Subject: [PATCH 51/51] chore(deps): bump org.apache.tomcat:tomcat-catalina from 9.0.108 to 11.0.27 (#6628) * chore(deps): bump org.apache.tomcat:tomcat-catalina Bumps org.apache.tomcat:tomcat-catalina from 9.0.108 to 11.0.27. --- updated-dependencies: - dependency-name: org.apache.tomcat:tomcat-catalina dependency-version: 11.0.27 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] * Apply suggestion from @runningcode --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Nelson Osacky --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index d0afe5ebd8a..5cf78106317 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -268,7 +268,7 @@ java8-signature = { module = "org.codehaus.mojo.signature:java18", version.ref = # 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" }