diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index dd207c3ef69..9a2c6f6d931 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -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 ()V public fun isClassAvailable (Ljava/lang/String;Lio/sentry/ILogger;)Z 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 104d2f0c803..bd8f4d791c4 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 @@ -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; @@ -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; @@ -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); + } + + /** 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. */ 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 b131a0af3e7..c8d9039a452 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java @@ -20,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; @@ -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 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."); @@ -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 -> { @@ -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 @@ -202,6 +211,7 @@ public static void init( deduplicateIntegrations(options, isFragmentAvailable, isTimberAvailable); }, + runtime, true); final @NotNull IScopes scopes = Sentry.getCurrentScopes(); diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 8dd75b41add..7dde4d7bf74 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -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 @@ -5446,6 +5447,17 @@ public final class io/sentry/instrumentation/file/SentryFileWriter : java/io/Out public fun (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 @@ -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; } diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index 8112cf0ee8b..aa8fdff4eb3 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -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; @@ -246,9 +249,26 @@ public static 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 void init( + final @NotNull OptionsContainer clazz, + final @NotNull OptionsConfiguration 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); } /** @@ -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()) { @@ -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( @@ -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() @@ -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); diff --git a/sentry/src/main/java/io/sentry/internal/InternalIntegration.java b/sentry/src/main/java/io/sentry/internal/InternalIntegration.java new file mode 100644 index 00000000000..34fb2180426 --- /dev/null +++ b/sentry/src/main/java/io/sentry/internal/InternalIntegration.java @@ -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); +} diff --git a/sentry/src/main/java/io/sentry/internal/LazySerializer.java b/sentry/src/main/java/io/sentry/internal/LazySerializer.java new file mode 100644 index 00000000000..4cb875c06ca --- /dev/null +++ b/sentry/src/main/java/io/sentry/internal/LazySerializer.java @@ -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 serializer; + + LazySerializer(final @NotNull LazyEvaluator.Evaluator serializer) { + this.serializer = new LazyEvaluator<>(serializer); + } + + @Override + public @Nullable T deserializeCollection( + final @NotNull Reader reader, + final @NotNull Class clazz, + final @Nullable JsonDeserializer elementDeserializer) { + return serializer.getValue().deserializeCollection(reader, clazz, elementDeserializer); + } + + @Override + public @Nullable T deserialize(final @NotNull Reader reader, final @NotNull Class clazz) { + return serializer.getValue().deserialize(reader, clazz); + } + + @Override + public @Nullable SentryEnvelope deserializeEnvelope(final @NotNull InputStream inputStream) { + return serializer.getValue().deserializeEnvelope(inputStream); + } + + @Override + public 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 data) throws Exception { + return serializer.getValue().serialize(data); + } +} diff --git a/sentry/src/main/java/io/sentry/internal/LegacyOptionsBridge.java b/sentry/src/main/java/io/sentry/internal/LegacyOptionsBridge.java new file mode 100644 index 00000000000..bcfd94974e1 --- /dev/null +++ b/sentry/src/main/java/io/sentry/internal/LegacyOptionsBridge.java @@ -0,0 +1,79 @@ +package io.sentry.internal; + +import io.sentry.ISentryExecutorService; +import io.sentry.NoOpSentryExecutorService; +import io.sentry.SentryExecutorService; +import io.sentry.SentryOptions; +import io.sentry.cache.IEnvelopeCache; +import io.sentry.transport.NoOpEnvelopeCache; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** + * Keeps the collaborator accessors on {@link SentryOptions} working until 9.0 removes them. Once + * the SDK reads its collaborators from {@link SentryRuntime}, this is the only SDK code that may + * call them; delete it together with them. + */ +@ApiStatus.Internal +public final class LegacyOptionsBridge { + + private LegacyOptionsBridge() {} + + /** + * Builds the runtime, letting a collaborator set through a {@link SentryOptions} setter win over + * the platform's, as it did before the runtime existed. Then copies the result back so code that + * still reads the getters sees the same instances. + */ + public static @NotNull SentryRuntime buildRuntime( + final @NotNull SentryRuntime.Builder builder, final @NotNull SentryOptions options) { + // Shares the options' lazy serializer, so the expensive JsonSerializer is created only once. + builder.lazySerializer(() -> options.getSerializer()); + + if (!builder.hasExecutorService()) { + builder.executorService(executorOrNew(options)); + } + + final @NotNull IEnvelopeCache envelopeDiskCache = options.getEnvelopeDiskCache(); + if (!(envelopeDiskCache instanceof NoOpEnvelopeCache)) { + builder.envelopeDiskCache(envelopeDiskCache); + } + + final @NotNull SentryRuntime runtime = builder.build(options); + options.setExecutorService(runtime.getExecutorService()); + options.setEnvelopeDiskCache(runtime.getEnvelopeDiskCache()); + return runtime; + } + + /** + * The executor a platform's init should hand out: the one already on {@code options}, unless + * there is none or a previous init that reused this options object closed it. + */ + public static @NotNull ISentryExecutorService executorOrNew( + final @NotNull SentryOptions options) { + final @NotNull ISentryExecutorService executorService = options.getExecutorService(); + if (executorService instanceof NoOpSentryExecutorService || executorService.isClosed()) { + return new SentryExecutorService(options); + } + return executorService; + } + + /** + * The executor for code that can't have it injected on 8.x, such as a public constructor that + * only takes {@link SentryOptions}. Each caller needs a replacement in 9.0. + */ + public static @NotNull ISentryExecutorService executorOf(final @NotNull SentryOptions options) { + return options.getExecutorService(); + } + + /** + * A runtime over the collaborators already on {@code options}, for an {@link InternalIntegration} + * registered without one. It creates nothing. + */ + public static @NotNull SentryRuntime runtimeOf(final @NotNull SentryOptions options) { + return SentryRuntime.builder() + .lazySerializer(() -> options.getSerializer()) + .executorService(options.getExecutorService()) + .envelopeDiskCache(options.getEnvelopeDiskCache()) + .build(options); + } +} diff --git a/sentry/src/main/java/io/sentry/internal/SentryRuntime.java b/sentry/src/main/java/io/sentry/internal/SentryRuntime.java new file mode 100644 index 00000000000..9a9dc673012 --- /dev/null +++ b/sentry/src/main/java/io/sentry/internal/SentryRuntime.java @@ -0,0 +1,134 @@ +package io.sentry.internal; + +import io.sentry.ISentryExecutorService; +import io.sentry.ISerializer; +import io.sentry.JsonSerializer; +import io.sentry.SentryExecutorService; +import io.sentry.SentryOptions; +import io.sentry.cache.EnvelopeCache; +import io.sentry.cache.IEnvelopeCache; +import io.sentry.transport.NoOpEnvelopeCache; +import io.sentry.util.LazyEvaluator; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.TestOnly; + +/** + * The SDK's own collaborators, built once per {@code Sentry.init}. Customers configure {@link + * SentryOptions}; the SDK owns this. + * + *

Components take the collaborators they use as constructor parameters instead of this whole + * object. Only the places that wire components together read from it. + */ +@ApiStatus.Internal +public final class SentryRuntime { + + private static volatile @Nullable SentryRuntime current; + + private final @Nullable ISerializer serializer; + private final @Nullable ISentryExecutorService executorService; + private final @Nullable IEnvelopeCache envelopeDiskCache; + + private SentryRuntime(final @NotNull Builder builder) { + this.serializer = builder.serializer; + this.executorService = builder.executorService; + this.envelopeDiskCache = builder.envelopeDiskCache; + } + + public static @NotNull Builder builder() { + return new Builder(); + } + + /** + * The runtime of the current {@code Sentry.init}, for hybrid SDKs that call in from outside and + * have no other way to reach it. SDK code gets its collaborators passed in instead. + */ + public static @Nullable SentryRuntime getCurrent() { + return current; + } + + public static void setCurrent(final @Nullable SentryRuntime runtime) { + current = runtime; + } + + public @NotNull ISerializer getSerializer() { + return require(serializer, "serializer"); + } + + public @NotNull ISentryExecutorService getExecutorService() { + return require(executorService, "executorService"); + } + + public @NotNull IEnvelopeCache getEnvelopeDiskCache() { + return require(envelopeDiskCache, "envelopeDiskCache"); + } + + private static @NotNull T require(final @Nullable T value, final @NotNull String name) { + if (value == null) { + // Only a runtime from buildForTest() has unset collaborators. + throw new IllegalStateException(name + " was not set on this test's SentryRuntime"); + } + return value; + } + + public static final class Builder { + private @Nullable ISerializer serializer; + private @Nullable ISentryExecutorService executorService; + private @Nullable IEnvelopeCache envelopeDiskCache; + + private Builder() {} + + public @NotNull Builder serializer(final @NotNull ISerializer serializer) { + this.serializer = serializer; + return this; + } + + /** Defers creating the serializer, which is expensive, until something first uses it. */ + public @NotNull Builder lazySerializer( + final @NotNull LazyEvaluator.Evaluator serializer) { + this.serializer = new LazySerializer(serializer); + return this; + } + + public @NotNull Builder executorService(final @NotNull ISentryExecutorService executorService) { + this.executorService = executorService; + return this; + } + + public @NotNull Builder envelopeDiskCache(final @NotNull IEnvelopeCache envelopeDiskCache) { + this.envelopeDiskCache = envelopeDiskCache; + return this; + } + + public boolean hasExecutorService() { + return executorService != null; + } + + /** Creates the default for every collaborator that wasn't set. */ + public @NotNull SentryRuntime build(final @NotNull SentryOptions options) { + if (serializer == null) { + lazySerializer(() -> new JsonSerializer(options)); + } + if (executorService == null) { + executorService = new SentryExecutorService(options); + } + if (envelopeDiskCache == null) { + envelopeDiskCache = + options.getCacheDirPath() != null + ? EnvelopeCache.create(options) + : NoOpEnvelopeCache.getInstance(); + } + return new SentryRuntime(this); + } + + /** + * Leaves unset collaborators unset, so a test that reads one it didn't set fails instead of + * silently getting a default. + */ + @TestOnly + public @NotNull SentryRuntime buildForTest() { + return new SentryRuntime(this); + } + } +} diff --git a/sentry/src/test/java/io/sentry/internal/SentryRuntimeTest.kt b/sentry/src/test/java/io/sentry/internal/SentryRuntimeTest.kt new file mode 100644 index 00000000000..aba6b02a6ad --- /dev/null +++ b/sentry/src/test/java/io/sentry/internal/SentryRuntimeTest.kt @@ -0,0 +1,118 @@ +package io.sentry.internal + +import com.google.common.truth.Truth.assertThat +import io.sentry.ISentryExecutorService +import io.sentry.ISerializer +import io.sentry.SentryOptions +import io.sentry.cache.EnvelopeCache +import io.sentry.cache.IEnvelopeCache +import io.sentry.transport.NoOpEnvelopeCache +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertFailsWith +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +class SentryRuntimeTest { + + @Test + fun `build creates a disk cache when a cache dir is set`() { + val options = + SentryOptions().apply { cacheDirPath = Files.createTempDirectory("sentry").toString() } + + val runtime = SentryRuntime.builder().build(options) + + assertThat(runtime.envelopeDiskCache).isInstanceOf(EnvelopeCache::class.java) + } + + @Test + fun `build uses a no-op disk cache without a cache dir`() { + val runtime = SentryRuntime.builder().build(SentryOptions()) + + assertThat(runtime.envelopeDiskCache).isSameInstanceAs(NoOpEnvelopeCache.getInstance()) + } + + @Test + fun `the serializer is created on first use, not when it's read`() { + var created = 0 + val runtime = + SentryRuntime.builder() + .lazySerializer { + created++ + mock() + } + .buildForTest() + + val serializer = runtime.serializer + assertThat(created).isEqualTo(0) + + serializer.serialize(mapOf("a" to 1)) + serializer.serialize(mapOf("b" to 2)) + assertThat(created).isEqualTo(1) + } + + @Test + fun `a test runtime fails on a collaborator the test didn't set`() { + val runtime = SentryRuntime.builder().envelopeDiskCache(mock()).buildForTest() + + val error = assertFailsWith { runtime.executorService } + assertThat(error).hasMessageThat().contains("executorService") + } + + @Test + fun `a cache set through the options setter wins over the platform's`() { + val customerCache = mock() + val options = SentryOptions().apply { setEnvelopeDiskCache(customerCache) } + + val runtime = + LegacyOptionsBridge.buildRuntime( + SentryRuntime.builder().envelopeDiskCache(mock()), + options, + ) + + assertThat(runtime.envelopeDiskCache).isSameInstanceAs(customerCache) + } + + @Test + fun `the options getters see the runtime's collaborators`() { + val platformCache = mock() + val options = SentryOptions() + + val runtime = + LegacyOptionsBridge.buildRuntime( + SentryRuntime.builder().envelopeDiskCache(platformCache), + options, + ) + + assertThat(options.envelopeDiskCache).isSameInstanceAs(platformCache) + assertThat(options.executorService).isSameInstanceAs(runtime.executorService) + } + + @Test + fun `a closed executor from a previous init is replaced`() { + val closed = mock() + whenever(closed.isClosed).thenReturn(true) + val options = SentryOptions().apply { executorService = closed } + + val runtime = LegacyOptionsBridge.buildRuntime(SentryRuntime.builder(), options) + + assertThat(runtime.executorService).isNotSameInstanceAs(closed) + runtime.executorService.close(0) + } + + @Test + fun `runtimeOf reuses the collaborators on the options`() { + val executor = mock() + val cache = mock() + val options = + SentryOptions().apply { + executorService = executor + setEnvelopeDiskCache(cache) + } + + val runtime = LegacyOptionsBridge.runtimeOf(options) + + assertThat(runtime.executorService).isSameInstanceAs(executor) + assertThat(runtime.envelopeDiskCache).isSameInstanceAs(cache) + } +}