Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
### Fixes

- Allow multiple UncaughtExceptionHandlerIntegrations to be active at the same time ([#4462](https://github.com/getsentry/sentry-java/pull/4462))
- Cache network capabilities and status to reduce IPC calls ([#4560](https://github.com/getsentry/sentry-java/pull/4560))
- Deduplicate battery breadcrumbs ([#4561](https://github.com/getsentry/sentry-java/pull/4561))
- Have single `NetworkCallback` registered at a time to reduce IPC calls ([#4562](https://github.com/getsentry/sentry-java/pull/4562))

## 8.17.0

Expand Down
2 changes: 1 addition & 1 deletion sentry-android-core/api/sentry-android-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ public final class io/sentry/android/core/NdkIntegration : io/sentry/Integration
}

public final class io/sentry/android/core/NetworkBreadcrumbsIntegration : io/sentry/Integration, java/io/Closeable {
public fun <init> (Landroid/content/Context;Lio/sentry/android/core/BuildInfoProvider;Lio/sentry/ILogger;)V
public fun <init> (Landroid/content/Context;Lio/sentry/android/core/BuildInfoProvider;)V
public fun close ()V
public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import io.sentry.android.core.internal.gestures.AndroidViewGestureTargetLocator;
import io.sentry.android.core.internal.modules.AssetsModulesLoader;
import io.sentry.android.core.internal.util.AndroidConnectionStatusProvider;
import io.sentry.android.core.internal.util.AndroidCurrentDateProvider;
import io.sentry.android.core.internal.util.AndroidThreadChecker;
import io.sentry.android.core.internal.util.SentryFrameMetricsCollector;
import io.sentry.android.core.performance.AppStartMetrics;
Expand Down Expand Up @@ -157,7 +158,8 @@ static void initializeIntegrationsAndProcessors(

if (options.getConnectionStatusProvider() instanceof NoOpConnectionStatusProvider) {
options.setConnectionStatusProvider(
new AndroidConnectionStatusProvider(context, options.getLogger(), buildInfoProvider));
new AndroidConnectionStatusProvider(
context, options, buildInfoProvider, AndroidCurrentDateProvider.getInstance()));
}

if (options.getCacheDirPath() != null) {
Expand Down Expand Up @@ -380,8 +382,7 @@ static void installDefaultIntegrations(
}
options.addIntegration(new AppComponentsBreadcrumbsIntegration(context));
options.addIntegration(new SystemEventsBreadcrumbsIntegration(context));
options.addIntegration(
new NetworkBreadcrumbsIntegration(context, buildInfoProvider, options.getLogger()));
options.addIntegration(new NetworkBreadcrumbsIntegration(context, buildInfoProvider));
if (isReplayAvailable) {
final ReplayIntegration replay =
new ReplayIntegration(context, CurrentDateProvider.getInstance());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import io.sentry.Breadcrumb;
import io.sentry.DateUtils;
import io.sentry.Hint;
import io.sentry.ILogger;
import io.sentry.IScopes;
import io.sentry.ISentryLifecycleToken;
import io.sentry.Integration;
Expand All @@ -33,22 +32,17 @@ public final class NetworkBreadcrumbsIntegration implements Integration, Closeab

private final @NotNull Context context;
private final @NotNull BuildInfoProvider buildInfoProvider;
private final @NotNull ILogger logger;
private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock();
private volatile boolean isClosed;
private @Nullable SentryOptions options;

@TestOnly @Nullable volatile NetworkBreadcrumbsNetworkCallback networkCallback;

public NetworkBreadcrumbsIntegration(
final @NotNull Context context,
final @NotNull BuildInfoProvider buildInfoProvider,
final @NotNull ILogger logger) {
final @NotNull Context context, final @NotNull BuildInfoProvider buildInfoProvider) {
this.context =
Objects.requireNonNull(ContextUtils.getApplicationContext(context), "Context is required");
this.buildInfoProvider =
Objects.requireNonNull(buildInfoProvider, "BuildInfoProvider is required");
this.logger = Objects.requireNonNull(logger, "ILogger is required");
}

@Override
Expand All @@ -59,87 +53,61 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions
(options instanceof SentryAndroidOptions) ? (SentryAndroidOptions) options : null,
"SentryAndroidOptions is required");

logger.log(
SentryLevel.DEBUG,
"NetworkBreadcrumbsIntegration enabled: %s",
androidOptions.isEnableNetworkEventBreadcrumbs());

this.options = options;

options
.getLogger()
.log(
SentryLevel.DEBUG,
"NetworkBreadcrumbsIntegration enabled: %s",
androidOptions.isEnableNetworkEventBreadcrumbs());

if (androidOptions.isEnableNetworkEventBreadcrumbs()) {

// The specific error is logged in the ConnectivityChecker method
if (buildInfoProvider.getSdkInfoVersion() < Build.VERSION_CODES.N) {
logger.log(SentryLevel.DEBUG, "NetworkCallbacks need Android N+.");
options.getLogger().log(SentryLevel.DEBUG, "NetworkCallbacks need Android N+.");
return;
}

try {
options
.getExecutorService()
.submit(
new Runnable() {
@Override
public void run() {
// in case integration is closed before the task is executed, simply return
if (isClosed) {
return;
}

try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) {
networkCallback =
new NetworkBreadcrumbsNetworkCallback(
scopes, buildInfoProvider, options.getDateProvider());

final boolean registered =
AndroidConnectionStatusProvider.registerNetworkCallback(
context, logger, buildInfoProvider, networkCallback);
if (registered) {
logger.log(SentryLevel.DEBUG, "NetworkBreadcrumbsIntegration installed.");
addIntegrationToSdkVersion("NetworkBreadcrumbs");
} else {
logger.log(
SentryLevel.DEBUG, "NetworkBreadcrumbsIntegration not installed.");
// The specific error is logged by AndroidConnectionStatusProvider
}
}
}
});
} catch (Throwable t) {
logger.log(SentryLevel.ERROR, "Error submitting NetworkBreadcrumbsIntegration task.", t);
try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) {
networkCallback =
new NetworkBreadcrumbsNetworkCallback(
scopes, buildInfoProvider, options.getDateProvider());

final boolean registered =
AndroidConnectionStatusProvider.addNetworkCallback(
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one caveat: This now will not emit AVAILABLE and CAPABILITIES_CHANGED callbacks immediately after registration as opposed to calling ConnectivityManager.registerDefaultNetworkCallback.

But I think it's fine and how it should be - previously any event would always start with NETWORK_AVAILABLE breadcrumb, which could have been misleading, now we're actually adding breadcrumbs whenever there's a change.

context, options.getLogger(), buildInfoProvider, networkCallback);
if (registered) {
options.getLogger().log(SentryLevel.DEBUG, "NetworkBreadcrumbsIntegration installed.");
addIntegrationToSdkVersion("NetworkBreadcrumbs");
} else {
options
.getLogger()
.log(SentryLevel.DEBUG, "NetworkBreadcrumbsIntegration not installed.");
// The specific error is logged by AndroidConnectionStatusProvider
}
}
}
}

@Override
public void close() throws IOException {
isClosed = true;
final @Nullable ConnectivityManager.NetworkCallback callbackRef;
try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) {
callbackRef = networkCallback;
networkCallback = null;
}

try {
Objects.requireNonNull(options, "Options is required")
.getExecutorService()
.submit(
() -> {
try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) {
if (networkCallback != null) {
AndroidConnectionStatusProvider.unregisterNetworkCallback(
context, logger, networkCallback);
logger.log(SentryLevel.DEBUG, "NetworkBreadcrumbsIntegration removed.");
}
networkCallback = null;
}
});
} catch (Throwable t) {
logger.log(SentryLevel.ERROR, "Error submitting NetworkBreadcrumbsIntegration task.", t);
if (callbackRef != null) {
AndroidConnectionStatusProvider.removeNetworkCallback(callbackRef);
}
}

static final class NetworkBreadcrumbsNetworkCallback extends ConnectivityManager.NetworkCallback {
final @NotNull IScopes scopes;
final @NotNull BuildInfoProvider buildInfoProvider;

@Nullable Network currentNetwork = null;

@Nullable NetworkCapabilities lastCapabilities = null;
long lastCapabilityNanos = 0;
final @NotNull SentryDateProvider dateProvider;
Expand All @@ -156,21 +124,14 @@ static final class NetworkBreadcrumbsNetworkCallback extends ConnectivityManager

@Override
public void onAvailable(final @NonNull Network network) {
if (network.equals(currentNetwork)) {
return;
}
final Breadcrumb breadcrumb = createBreadcrumb("NETWORK_AVAILABLE");
scopes.addBreadcrumb(breadcrumb);
currentNetwork = network;
lastCapabilities = null;
}

@Override
public void onCapabilitiesChanged(
final @NonNull Network network, final @NonNull NetworkCapabilities networkCapabilities) {
if (!network.equals(currentNetwork)) {
return;
}
final long nowNanos = dateProvider.now().nanoTimestamp();
final @Nullable NetworkBreadcrumbConnectionDetail connectionDetail =
getNewConnectionDetails(
Expand All @@ -195,12 +156,8 @@ public void onCapabilitiesChanged(

@Override
public void onLost(final @NonNull Network network) {
if (!network.equals(currentNetwork)) {
return;
}
final Breadcrumb breadcrumb = createBreadcrumb("NETWORK_LOST");
scopes.addBreadcrumb(breadcrumb);
currentNetwork = null;
lastCapabilities = null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ public void close() throws IOException {
@Override
public void onConnectionStatusChanged(
final @NotNull IConnectionStatusProvider.ConnectionStatus status) {
if (scopes != null && options != null) {
if (scopes != null
&& options != null
&& status != IConnectionStatusProvider.ConnectionStatus.DISCONNECTED) {
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kind of unrelated to this PR, but I noticed that we also submit a task even if the status was DISCONNECTED, which was unnecessary since we'd anyway bail out in the submitted task itself.

sendCachedEnvelopes(scopes, options);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,43 @@ static final class SystemEventsBroadcastReceiver extends BroadcastReceiver {
private final @NotNull Debouncer batteryChangedDebouncer =
new Debouncer(AndroidCurrentDateProvider.getInstance(), DEBOUNCE_WAIT_TIME_MS, 0);

// Track previous battery state to avoid duplicate breadcrumbs when values haven't changed
private @Nullable BatteryState previousBatteryState;

static final class BatteryState {
private final @Nullable Float level;
private final @Nullable Boolean charging;

BatteryState(final @Nullable Float level, final @Nullable Boolean charging) {
this.level = level;
this.charging = charging;
}

@Override
public boolean equals(final @Nullable Object other) {
if (!(other instanceof BatteryState)) return false;
BatteryState that = (BatteryState) other;
return isSimilarLevel(level, that.level) && Objects.equals(charging, that.charging);
}

@Override
public int hashCode() {
// Use rounded level for hash consistency
Float roundedLevel = level != null ? Math.round(level * 100f) / 100f : null;
return Objects.hash(roundedLevel, charging);
}

private boolean isSimilarLevel(final @Nullable Float level1, final @Nullable Float level2) {
if (level1 == null && level2 == null) return true;
if (level1 == null || level2 == null) return false;

// Round both levels to 2 decimal places and compare
float rounded1 = Math.round(level1 * 100f) / 100f;
float rounded2 = Math.round(level2 * 100f) / 100f;
return rounded1 == rounded2;
}
}

SystemEventsBroadcastReceiver(
final @NotNull IScopes scopes, final @NotNull SentryAndroidOptions options) {
this.scopes = scopes;
Expand All @@ -350,19 +387,34 @@ public void onReceive(final Context context, final @NotNull Intent intent) {
final @Nullable String action = intent.getAction();
final boolean isBatteryChanged = ACTION_BATTERY_CHANGED.equals(action);

// aligning with iOS which only captures battery status changes every minute at maximum
if (isBatteryChanged && batteryChangedDebouncer.checkForDebounce()) {
return;
@Nullable BatteryState batteryState = null;
if (isBatteryChanged) {
if (batteryChangedDebouncer.checkForDebounce()) {
// aligning with iOS which only captures battery status changes every minute at maximum
return;
}

// For battery changes, check if the actual values have changed
final @Nullable Float currentBatteryLevel = DeviceInfoUtil.getBatteryLevel(intent, options);
final @Nullable Boolean currentChargingState = DeviceInfoUtil.isCharging(intent, options);
batteryState = new BatteryState(currentBatteryLevel, currentChargingState);

// Only create breadcrumb if battery state has actually changed
if (batteryState.equals(previousBatteryState)) {
return;
}

previousBatteryState = batteryState;
}

final BatteryState state = batteryState;
final long now = System.currentTimeMillis();
try {
options
.getExecutorService()
.submit(
() -> {
final Breadcrumb breadcrumb =
createBreadcrumb(now, intent, action, isBatteryChanged);
final Breadcrumb breadcrumb = createBreadcrumb(now, intent, action, state);
final Hint hint = new Hint();
hint.set(ANDROID_INTENT, intent);
scopes.addBreadcrumb(breadcrumb, hint);
Expand Down Expand Up @@ -411,7 +463,7 @@ String getStringAfterDotFast(final @Nullable String str) {
final long timeMs,
final @NotNull Intent intent,
final @Nullable String action,
boolean isBatteryChanged) {
final @Nullable BatteryState batteryState) {
final Breadcrumb breadcrumb = new Breadcrumb(timeMs);
breadcrumb.setType("system");
breadcrumb.setCategory("device.event");
Expand All @@ -420,14 +472,12 @@ String getStringAfterDotFast(final @Nullable String str) {
breadcrumb.setData("action", shortAction);
}

if (isBatteryChanged) {
final Float batteryLevel = DeviceInfoUtil.getBatteryLevel(intent, options);
if (batteryLevel != null) {
breadcrumb.setData("level", batteryLevel);
if (batteryState != null) {
if (batteryState.level != null) {
breadcrumb.setData("level", batteryState.level);
}
final Boolean isCharging = DeviceInfoUtil.isCharging(intent, options);
if (isCharging != null) {
breadcrumb.setData("charging", isCharging);
if (batteryState.charging != null) {
breadcrumb.setData("charging", batteryState.charging);
}
} else {
final Bundle extras = intent.getExtras();
Expand Down
Loading
Loading