Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions sentry-android-core/api/sentry-android-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -330,11 +330,17 @@ public final class io/sentry/android/core/InternalSentrySdk {
public static fun captureEnvelopeNonTerminating ([B)Lio/sentry/protocol/SentryId;
public static fun getAppStartMeasurement ()Ljava/util/Map;
public static fun getCurrentScope ()Lio/sentry/IScope;
public static fun getRuntime ()Lio/sentry/internal/SentryRuntime;
public static fun init (Landroid/content/Context;Lio/sentry/ILogger;Lio/sentry/android/core/InternalSentrySdk$OptionsAndRuntimeConfiguration;)V
public static fun serializeScope (Landroid/content/Context;Lio/sentry/android/core/SentryAndroidOptions;Lio/sentry/IScope;)Ljava/util/Map;
public static fun setTrace (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Double;Ljava/lang/Double;)V
public static fun updateSessionForDroppedEventNonTerminating (Z)V
}

public abstract interface class io/sentry/android/core/InternalSentrySdk$OptionsAndRuntimeConfiguration {
public abstract fun configure (Lio/sentry/android/core/SentryAndroidOptions;Lio/sentry/internal/SentryRuntime$Builder;)V
}

public final class io/sentry/android/core/LoadClass : io/sentry/util/LoadClass {
public fun <init> ()V
public fun isClassAvailable (Ljava/lang/String;Lio/sentry/ILogger;)Z
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import io.sentry.PropagationContext;
import io.sentry.ScopeType;
import io.sentry.ScopesAdapter;
import io.sentry.Sentry;
import io.sentry.SentryEnvelope;
import io.sentry.SentryEnvelopeItem;
import io.sentry.SentryEvent;
Expand All @@ -26,6 +27,7 @@
import io.sentry.android.core.performance.AppStartMetrics;
import io.sentry.android.core.performance.TimeSpan;
import io.sentry.cache.EnvelopeCache;
import io.sentry.internal.SentryRuntime;
import io.sentry.protocol.App;
import io.sentry.protocol.Device;
import io.sentry.protocol.SentryId;
Expand All @@ -50,6 +52,27 @@
@ApiStatus.Internal
public final class InternalSentrySdk {

/** Configures both the options and the SDK's own collaborators. */
public interface OptionsAndRuntimeConfiguration {
void configure(@NotNull SentryAndroidOptions options, @NotNull SentryRuntime.Builder runtime);
}

/**
* Like {@link SentryAndroid#init(Context, ILogger, Sentry.OptionsConfiguration)}, but also lets
* the hybrid SDK set the SDK's own collaborators.
*/
public static void init(
final @NotNull Context context,
final @NotNull ILogger logger,
final @NotNull OptionsAndRuntimeConfiguration configuration) {
SentryAndroid.init(context, logger, configuration);
}

Check warning on line 69 in sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java

View check run for this annotation

@sentry/warden / warden: code-review

Hybrid init with profiling leaks the executor created before the runtime override

When a hybrid config supplies `runtime.executorService(...)` and enables profiling, `activate()` creates an executor on options and `initConfigurations()` submits profiling cleanup to it before the runtime replaces it; `Sentry.close()` closes only the replacement, leaving the original worker alive.
Comment on lines +64 to +69

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hybrid init with profiling leaks the executor created before the runtime override

When a hybrid config supplies runtime.executorService(...) and enables profiling, activate() creates an executor on options and initConfigurations() submits profiling cleanup to it before the runtime replaces it; Sentry.close() closes only the replacement, leaving the original worker alive.

Evidence
  • InternalSentrySdk.init passes the builder to the configuration callback, so a hybrid can set runtime.executorService(...) without setting the options executor.
  • Sentry.init calls options.activate() before initConfigurations() and builds the runtime afterward. With the options executor unset, activate() creates a SentryExecutorService; when profiling is enabled, initConfigurations() submits cleanup to it. Android initialization supplies a cache path, so the profiling-traces path is available.
  • LegacyOptionsBridge.buildRuntime then replaces the options executor with the builderโ€™s executor without closing the previous one. The default SentryExecutorService does not time out its core worker, and Sentry.close() closes only the executor currently on options.
Also found at 1 additional location
  • sentry/src/main/java/io/sentry/internal/LegacyOptionsBridge.java:32-43

Identified by Warden ยท code-review ยท CXK-F6A


/** The SDK's own collaborators, or {@code null} before init and after close. */
public static @Nullable SentryRuntime getRuntime() {
return SentryRuntime.getCurrent();
}

/**
* Returns a copy of the current scopes's topmost scope, or null in case the scopes is disabled.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import io.sentry.android.core.performance.TimeSpan;
import io.sentry.android.fragment.FragmentLifecycleIntegration;
import io.sentry.android.timber.SentryTimberIntegration;
import io.sentry.internal.SentryRuntime;
import io.sentry.time.Stopwatch;
import io.sentry.util.AutoClosableReentrantLock;
import io.sentry.util.FileUtils;
Expand Down Expand Up @@ -103,11 +104,18 @@ public static void init(
* @param logger your custom logger that implements ILogger
* @param configuration Sentry.OptionsConfiguration configuration handler
*/
@SuppressLint("NewApi")
public static void init(
@NotNull final Context context,
@NotNull ILogger logger,
@NotNull Sentry.OptionsConfiguration<SentryAndroidOptions> configuration) {
init(context, logger, (options, runtime) -> configuration.configure(options));
}

@SuppressLint("NewApi")
static void init(
@NotNull final Context context,
@NotNull ILogger logger,
@NotNull InternalSentrySdk.OptionsAndRuntimeConfiguration configuration) {
if (isNdkCrashServiceProcess()) {
logger.log(
SentryLevel.DEBUG, "Skipping SentryAndroid.init in the NDK crash service process.");
Expand All @@ -118,6 +126,7 @@ public static void init(
// even if acquire() throws.
Trace.beginSection("SentryAndroid.init");
try (final @NotNull ISentryLifecycleToken ignored = staticLock.acquire()) {
final @NotNull SentryRuntime.Builder runtime = SentryRuntime.builder();
Sentry.init(
new SentryAndroidOptionsContainer(),
options -> {
Expand Down Expand Up @@ -161,7 +170,7 @@ public static void init(
isDistributionAvailable);

try {
configuration.configure(options);
configuration.configure(options, runtime);
} catch (Throwable t) {
// let it slip, but log it
options
Expand Down Expand Up @@ -202,6 +211,7 @@ public static void init(

deduplicateIntegrations(options, isFragmentAvailable, isTimberAvailable);
},
runtime,
true);

final @NotNull IScopes scopes = Sentry.getCurrentScopes();
Expand Down
31 changes: 31 additions & 0 deletions sentry/api/sentry.api
Original file line number Diff line number Diff line change
Expand Up @@ -2938,6 +2938,7 @@ public final class io/sentry/Sentry {
public static fun getTraceparent ()Lio/sentry/SentryTraceHeader;
public static fun init ()V
public static fun init (Lio/sentry/OptionsContainer;Lio/sentry/Sentry$OptionsConfiguration;)V
public static fun init (Lio/sentry/OptionsContainer;Lio/sentry/Sentry$OptionsConfiguration;Lio/sentry/internal/SentryRuntime$Builder;Z)V
public static fun init (Lio/sentry/OptionsContainer;Lio/sentry/Sentry$OptionsConfiguration;Z)V
public static fun init (Lio/sentry/Sentry$OptionsConfiguration;)V
public static fun init (Lio/sentry/Sentry$OptionsConfiguration;Z)V
Expand Down Expand Up @@ -5446,6 +5447,17 @@ public final class io/sentry/instrumentation/file/SentryFileWriter : java/io/Out
public fun <init> (Ljava/lang/String;Z)V
}

public abstract interface class io/sentry/internal/InternalIntegration : io/sentry/Integration {
public abstract fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;Lio/sentry/internal/SentryRuntime;)V
}

public final class io/sentry/internal/LegacyOptionsBridge {
public static fun buildRuntime (Lio/sentry/internal/SentryRuntime$Builder;Lio/sentry/SentryOptions;)Lio/sentry/internal/SentryRuntime;
public static fun executorOf (Lio/sentry/SentryOptions;)Lio/sentry/ISentryExecutorService;
public static fun executorOrNew (Lio/sentry/SentryOptions;)Lio/sentry/ISentryExecutorService;
public static fun runtimeOf (Lio/sentry/SentryOptions;)Lio/sentry/internal/SentryRuntime;
}

public final class io/sentry/internal/ManifestVersionReader {
public static fun getInstance ()Lio/sentry/internal/ManifestVersionReader;
public fun readManifestFiles ()V
Expand All @@ -5458,6 +5470,25 @@ public final class io/sentry/internal/ManifestVersionReader$VersionInfoHolder {
public fun getSdkVersion ()Ljava/lang/String;
}

public final class io/sentry/internal/SentryRuntime {
public static fun builder ()Lio/sentry/internal/SentryRuntime$Builder;
public static fun getCurrent ()Lio/sentry/internal/SentryRuntime;
public fun getEnvelopeDiskCache ()Lio/sentry/cache/IEnvelopeCache;
public fun getExecutorService ()Lio/sentry/ISentryExecutorService;
public fun getSerializer ()Lio/sentry/ISerializer;
public static fun setCurrent (Lio/sentry/internal/SentryRuntime;)V
}

public final class io/sentry/internal/SentryRuntime$Builder {
public fun build (Lio/sentry/SentryOptions;)Lio/sentry/internal/SentryRuntime;
public fun buildForTest ()Lio/sentry/internal/SentryRuntime;
public fun envelopeDiskCache (Lio/sentry/cache/IEnvelopeCache;)Lio/sentry/internal/SentryRuntime$Builder;
public fun executorService (Lio/sentry/ISentryExecutorService;)Lio/sentry/internal/SentryRuntime$Builder;
public fun hasExecutorService ()Z
public fun lazySerializer (Lio/sentry/util/LazyEvaluator$Evaluator;)Lio/sentry/internal/SentryRuntime$Builder;
public fun serializer (Lio/sentry/ISerializer;)Lio/sentry/internal/SentryRuntime$Builder;
}

public abstract interface class io/sentry/internal/debugmeta/IDebugMetaLoader {
public abstract fun loadDebugMeta ()Ljava/util/List;
}
Expand Down
48 changes: 40 additions & 8 deletions sentry/src/main/java/io/sentry/Sentry.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import io.sentry.cache.IEnvelopeCache;
import io.sentry.cache.PersistingScopeObserver;
import io.sentry.config.PropertiesProviderFactory;
import io.sentry.internal.InternalIntegration;
import io.sentry.internal.LegacyOptionsBridge;
import io.sentry.internal.SentryRuntime;
import io.sentry.internal.debugmeta.NoOpDebugMetaLoader;
import io.sentry.internal.debugmeta.ResourcesDebugMetaLoader;
import io.sentry.internal.modules.CompositeModulesLoader;
Expand Down Expand Up @@ -246,9 +249,26 @@ public static <T extends SentryOptions> void init(
InstantiationException,
NoSuchMethodException,
InvocationTargetException {
init(clazz, optionsConfiguration, SentryRuntime.builder(), globalHubMode);
}

/**
* Initializes the SDK, letting the platform's init add its own collaborators to {@code runtime}
* while it configures the options.
*/
@ApiStatus.Internal
public static <T extends SentryOptions> void init(
final @NotNull OptionsContainer<T> clazz,
final @NotNull OptionsConfiguration<T> optionsConfiguration,
final @NotNull SentryRuntime.Builder runtime,
final boolean globalHubMode)
throws IllegalAccessException,
InstantiationException,
NoSuchMethodException,
InvocationTargetException {
final T options = clazz.createInstance();
applyOptionsConfiguration(optionsConfiguration, options);
init(options, globalHubMode);
init(options, runtime, globalHubMode);
}

/**
Expand Down Expand Up @@ -301,12 +321,19 @@ public static void init(final @NotNull SentryOptions options) {
* @param options options the SentryOptions
* @param globalHubMode the globalHubMode
*/
private static void init(final @NotNull SentryOptions options, final boolean globalHubMode) {
init(options, SentryRuntime.builder(), globalHubMode);
}

@SuppressWarnings({
"deprecation",
"Convert2MethodRef",
"FutureReturnValueIgnored"
}) // older AGP versions do not support method references
private static void init(final @NotNull SentryOptions options, final boolean globalHubMode) {
private static void init(
final @NotNull SentryOptions options,
final @NotNull SentryRuntime.Builder runtimeBuilder,
final boolean globalHubMode) {
try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) {
if (!options.getClass().getName().equals("io.sentry.android.core.SentryAndroidOptions")
&& Platform.isAndroid()) {
Expand Down Expand Up @@ -356,11 +383,10 @@ private static void init(final @NotNull SentryOptions options, final boolean glo

globalScope.bindClient(new SentryClient(options));

// If the executorService passed in the init is the same that was previously closed, we have
// to set a new one
if (options.getExecutorService().isClosed()) {
options.setExecutorService(new SentryExecutorService(options));
}
// Also replaces an executor that a previous init closed, when the options are reused.
final @NotNull SentryRuntime runtime =
LegacyOptionsBridge.buildRuntime(runtimeBuilder, options);
SentryRuntime.setCurrent(runtime);

if (options.getTimerExecutorService().isClosed()) {
options.setTimerExecutorService(
Expand All @@ -387,7 +413,12 @@ private static void init(final @NotNull SentryOptions options, final boolean glo
// Registering integrations here make sure that Scopes is already created.
for (final Integration integration : options.getIntegrations()) {
try {
integration.register(ScopesAdapter.getInstance(), options);
if (integration instanceof InternalIntegration) {
((InternalIntegration) integration)
.register(ScopesAdapter.getInstance(), options, runtime);
} else {
integration.register(ScopesAdapter.getInstance(), options);
}
} catch (Throwable t) {
options
.getLogger()
Expand Down Expand Up @@ -741,6 +772,7 @@ public static void close() {
try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) {
final IScopes scopes = getCurrentScopes();
rootScopes = NoOpScopes.getInstance();
SentryRuntime.setCurrent(null);
// remove thread local to avoid memory leak
getScopesStorage().close();
scopes.close(false);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package io.sentry.internal;

import io.sentry.IScopes;
import io.sentry.Integration;
import io.sentry.SentryOptions;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;

/**
* An SDK integration that needs the SDK's own collaborators. Customers create integrations before
* {@code Sentry.init}, so they can't be constructor-injected; {@code Sentry.init} hands them over
* here instead.
*/
@ApiStatus.Internal
public interface InternalIntegration extends Integration {

void register(
@NotNull IScopes scopes, @NotNull SentryOptions options, @NotNull SentryRuntime runtime);
}
63 changes: 63 additions & 0 deletions sentry/src/main/java/io/sentry/internal/LazySerializer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package io.sentry.internal;

import io.sentry.ISerializer;
import io.sentry.JsonDeserializer;
import io.sentry.SentryEnvelope;
import io.sentry.util.LazyEvaluator;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
* Creates the real serializer, which is expensive, on first use, so components can take an {@link
* ISerializer} in their constructor without creating it during init.
*/
final class LazySerializer implements ISerializer {

private final @NotNull LazyEvaluator<ISerializer> serializer;

LazySerializer(final @NotNull LazyEvaluator.Evaluator<ISerializer> serializer) {
this.serializer = new LazyEvaluator<>(serializer);
}

@Override
public <T, R> @Nullable T deserializeCollection(
final @NotNull Reader reader,
final @NotNull Class<T> clazz,
final @Nullable JsonDeserializer<R> elementDeserializer) {
return serializer.getValue().deserializeCollection(reader, clazz, elementDeserializer);
}

@Override
public <T> @Nullable T deserialize(final @NotNull Reader reader, final @NotNull Class<T> clazz) {
return serializer.getValue().deserialize(reader, clazz);
}

@Override
public @Nullable SentryEnvelope deserializeEnvelope(final @NotNull InputStream inputStream) {
return serializer.getValue().deserializeEnvelope(inputStream);
}

@Override
public <T> void serialize(final @NotNull T entity, final @NotNull Writer writer)
throws IOException {
serializer.getValue().serialize(entity, writer);
}

@Override
public void serialize(
final @NotNull SentryEnvelope envelope, final @NotNull OutputStream outputStream)
throws Exception {
serializer.getValue().serialize(envelope, outputStream);
}

@Override
public @NotNull String serialize(final @NotNull Map<String, Object> data) throws Exception {
return serializer.getValue().serialize(data);
}
}
Loading
Loading