diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index dd207c3ef69..5a92e669d40 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 getInternalServices ()Lio/sentry/internal/InternalServices; + public static fun init (Landroid/content/Context;Lio/sentry/ILogger;Lio/sentry/android/core/InternalSentrySdk$OptionsAndServicesConfiguration;)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$OptionsAndServicesConfiguration { + public abstract fun configure (Lio/sentry/android/core/SentryAndroidOptions;Lio/sentry/internal/InternalServices$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..2480888b535 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.InternalServices; import io.sentry.protocol.App; import io.sentry.protocol.Device; import io.sentry.protocol.SentryId; @@ -50,6 +52,31 @@ @ApiStatus.Internal public final class InternalSentrySdk { + /** + * Configures both the options and the SDK's internal services. The executor is the exception: set + * it on the options, see {@link InternalServices.Builder#executorService}. + */ + public interface OptionsAndServicesConfiguration { + void configure( + @NotNull SentryAndroidOptions options, @NotNull InternalServices.Builder services); + } + + /** + * Like {@link SentryAndroid#init(Context, ILogger, Sentry.OptionsConfiguration)}, but also lets + * the hybrid SDK set the SDK's internal services. + */ + public static void init( + final @NotNull Context context, + final @NotNull ILogger logger, + final @NotNull OptionsAndServicesConfiguration configuration) { + SentryAndroid.init(context, logger, configuration); + } + + /** The SDK's internal services, or {@code null} before init and after close. */ + public static @Nullable InternalServices getInternalServices() { + return InternalServices.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..fe9fc7fea83 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.InternalServices; 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, services) -> configuration.configure(options)); + } + + @SuppressLint("NewApi") + static void init( + @NotNull final Context context, + @NotNull ILogger logger, + @NotNull InternalSentrySdk.OptionsAndServicesConfiguration 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 InternalServices.Builder services = InternalServices.builder(); Sentry.init( new SentryAndroidOptionsContainer(), options -> { @@ -161,7 +170,7 @@ public static void init( isDistributionAvailable); try { - configuration.configure(options); + configuration.configure(options, services); } catch (Throwable t) { // let it slip, but log it options @@ -202,6 +211,7 @@ public static void init( deduplicateIntegrations(options, isFragmentAvailable, isTimberAvailable); }, + services, true); final @NotNull IScopes scopes = Sentry.getCurrentScopes(); diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 3dc8ed74c4a..dc5c3c2a1c9 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/InternalServices$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,36 @@ 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/InternalServices;)V +} + +public final class io/sentry/internal/InternalServices { + public static fun builder ()Lio/sentry/internal/InternalServices$Builder; + public static fun getCurrent ()Lio/sentry/internal/InternalServices; + 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/InternalServices;)V +} + +public final class io/sentry/internal/InternalServices$Builder { + public fun build (Lio/sentry/SentryOptions;)Lio/sentry/internal/InternalServices; + public fun buildForTest ()Lio/sentry/internal/InternalServices; + public fun envelopeDiskCache (Lio/sentry/cache/IEnvelopeCache;)Lio/sentry/internal/InternalServices$Builder; + public fun executorService (Lio/sentry/ISentryExecutorService;)Lio/sentry/internal/InternalServices$Builder; + public fun hasExecutorService ()Z + public fun lazySerializer (Lio/sentry/util/LazyEvaluator$Evaluator;)Lio/sentry/internal/InternalServices$Builder; + public fun serializer (Lio/sentry/ISerializer;)Lio/sentry/internal/InternalServices$Builder; +} + +public final class io/sentry/internal/LegacyOptionsBridge { + public static fun buildServices (Lio/sentry/internal/InternalServices$Builder;Lio/sentry/SentryOptions;)Lio/sentry/internal/InternalServices; + public static fun executorOf (Lio/sentry/SentryOptions;)Lio/sentry/ISentryExecutorService; + public static fun executorOrNew (Lio/sentry/SentryOptions;)Lio/sentry/ISentryExecutorService; + public static fun servicesOf (Lio/sentry/SentryOptions;)Lio/sentry/internal/InternalServices; +} + public final class io/sentry/internal/ManifestVersionReader { public static fun getInstance ()Lio/sentry/internal/ManifestVersionReader; public fun readManifestFiles ()V diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index 8112cf0ee8b..c43f339b122 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.InternalServices; +import io.sentry.internal.LegacyOptionsBridge; 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, InternalServices.builder(), globalHubMode); + } + + /** + * Initializes the SDK, letting the platform's init add its own internal services to {@code + * services} while it configures the options. + */ + @ApiStatus.Internal + public static void init( + final @NotNull OptionsContainer clazz, + final @NotNull OptionsConfiguration optionsConfiguration, + final @NotNull InternalServices.Builder services, + final boolean globalHubMode) + throws IllegalAccessException, + InstantiationException, + NoSuchMethodException, + InvocationTargetException { final T options = clazz.createInstance(); applyOptionsConfiguration(optionsConfiguration, options); - init(options, globalHubMode); + init(options, services, 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, InternalServices.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 InternalServices.Builder servicesBuilder, + 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 InternalServices services = + LegacyOptionsBridge.buildServices(servicesBuilder, options); + InternalServices.setCurrent(services); 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, services); + } 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(); + InternalServices.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..5e984998bbe --- /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 internal services. 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 InternalServices services); +} diff --git a/sentry/src/main/java/io/sentry/internal/InternalServices.java b/sentry/src/main/java/io/sentry/internal/InternalServices.java new file mode 100644 index 00000000000..8d1d7480b48 --- /dev/null +++ b/sentry/src/main/java/io/sentry/internal/InternalServices.java @@ -0,0 +1,140 @@ +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 internal services, built once per {@code Sentry.init}. Customers configure {@link + * SentryOptions}; the SDK owns this. + * + *

Components take the internal services 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 InternalServices { + + private static volatile @Nullable InternalServices current; + + private final @Nullable ISerializer serializer; + private final @Nullable ISentryExecutorService executorService; + private final @Nullable IEnvelopeCache envelopeDiskCache; + + private InternalServices(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 internal services of the current {@code Sentry.init}, for hybrid SDKs that call in from + * outside and have no other way to reach them. SDK code gets its internal services passed in + * instead. + */ + public static @Nullable InternalServices getCurrent() { + return current; + } + + public static void setCurrent(final @Nullable InternalServices services) { + current = services; + } + + 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 buildForTest() leaves internal services unset. + throw new IllegalStateException(name + " was not set on this test's InternalServices"); + } + 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; + } + + /** + * For the platform's init only. On Android, an executor set here from a hybrid SDK's callback + * would replace one the SDK has already started using, and that one would never be closed. + * Until 9.0, hybrid SDKs set their executor through {@code SentryOptions.setExecutorService}. + */ + 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 internal service that wasn't set. */ + public @NotNull InternalServices 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 InternalServices(this); + } + + /** + * Leaves unset internal services unset, so a test that reads one it didn't set fails instead of + * silently getting a default. + */ + @TestOnly + public @NotNull InternalServices buildForTest() { + return new InternalServices(this); + } + } +} 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..9160ea6eda4 --- /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 internal-service accessors on {@link SentryOptions} working until 9.0 removes them. + * Once the SDK reads its internal services from {@link InternalServices}, 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 internal services, letting an internal service set through a {@link SentryOptions} + * setter win over the platform's, as it did before InternalServices existed. Then copies the + * result back so code that still reads the getters sees the same instances. + */ + public static @NotNull InternalServices buildServices( + final @NotNull InternalServices.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 InternalServices services = builder.build(options); + options.setExecutorService(services.getExecutorService()); + options.setEnvelopeDiskCache(services.getEnvelopeDiskCache()); + return services; + } + + /** + * 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(); + } + + /** + * The internal services already on {@code options}, for an {@link InternalIntegration} registered + * without them. It creates nothing. + */ + public static @NotNull InternalServices servicesOf(final @NotNull SentryOptions options) { + return InternalServices.builder() + .lazySerializer(() -> options.getSerializer()) + .executorService(options.getExecutorService()) + .envelopeDiskCache(options.getEnvelopeDiskCache()) + .build(options); + } +} diff --git a/sentry/src/test/java/io/sentry/internal/InternalServicesTest.kt b/sentry/src/test/java/io/sentry/internal/InternalServicesTest.kt new file mode 100644 index 00000000000..44a10348734 --- /dev/null +++ b/sentry/src/test/java/io/sentry/internal/InternalServicesTest.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 InternalServicesTest { + + @Test + fun `build creates a disk cache when a cache dir is set`() { + val options = + SentryOptions().apply { cacheDirPath = Files.createTempDirectory("sentry").toString() } + + val services = InternalServices.builder().build(options) + + assertThat(services.envelopeDiskCache).isInstanceOf(EnvelopeCache::class.java) + } + + @Test + fun `build uses a no-op disk cache without a cache dir`() { + val services = InternalServices.builder().build(SentryOptions()) + + assertThat(services.envelopeDiskCache).isSameInstanceAs(NoOpEnvelopeCache.getInstance()) + } + + @Test + fun `the serializer is created on first use, not when it's read`() { + var created = 0 + val services = + InternalServices.builder() + .lazySerializer { + created++ + mock() + } + .buildForTest() + + val serializer = services.serializer + assertThat(created).isEqualTo(0) + + serializer.serialize(mapOf("a" to 1)) + serializer.serialize(mapOf("b" to 2)) + assertThat(created).isEqualTo(1) + } + + @Test + fun `buildForTest fails on an internal service the test didn't set`() { + val services = InternalServices.builder().envelopeDiskCache(mock()).buildForTest() + + val error = assertFailsWith { services.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 services = + LegacyOptionsBridge.buildServices( + InternalServices.builder().envelopeDiskCache(mock()), + options, + ) + + assertThat(services.envelopeDiskCache).isSameInstanceAs(customerCache) + } + + @Test + fun `the options getters see the same internal services`() { + val platformCache = mock() + val options = SentryOptions() + + val services = + LegacyOptionsBridge.buildServices( + InternalServices.builder().envelopeDiskCache(platformCache), + options, + ) + + assertThat(options.envelopeDiskCache).isSameInstanceAs(platformCache) + assertThat(options.executorService).isSameInstanceAs(services.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 services = LegacyOptionsBridge.buildServices(InternalServices.builder(), options) + + assertThat(services.executorService).isNotSameInstanceAs(closed) + services.executorService.close(0) + } + + @Test + fun `servicesOf reuses the internal services on the options`() { + val executor = mock() + val cache = mock() + val options = + SentryOptions().apply { + executorService = executor + setEnvelopeDiskCache(cache) + } + + val services = LegacyOptionsBridge.servicesOf(options) + + assertThat(services.executorService).isSameInstanceAs(executor) + assertThat(services.envelopeDiskCache).isSameInstanceAs(cache) + } +}